java 中自定义类位置以及修饰符等引发的问题

1:正确的形式

Text.java文件:

package lei.com.cn;

 public class Test {
  
     void fun(Mytype j)
    {
        j.a=2;
        System.out.println("fun函数后复杂数据类型参数j的值:"+j.a);
    }    
    
    public static void main(String[] args) {
        Mytype type=new Mytype();
        System.out.println("初始阶段复杂数据类型type的值:"+type.a);
        Test test=new Test();
        test.fun(type);
        System.out.println("调用函数后type的值:"+type.a);
        
    }
}

 class Mytype{
    public int a;
    public Mytype(){
        a=1;
    }
}

说明与文件名相同的类必须定义为Public 如上图public class Test,如果没有public虽不会报错,但一般系统默认自动生成public修饰符。

而自定义的类,注意位置不是内部类。不能是public,不然会报错“The public type Mytype must be defined in its own file”。

所以说一个Java文件中至多有一个public类。当有一个public类时,源文件名必须与之一致,否则无法编。

2.这种情况

package lei.com.cn;

 class Test {

     void fun(Mytype j)
    {
        j.a=2;
        System.out.println("fun函数后复杂数据类型参数j的值:"+j.a);
    }    
    
    public static void main(String[] args) {
        Mytype type=new Mytype();
        System.out.println("初始阶段复杂数据类型type的值:"+type.a);
        Test test=new Test();
        test.fun(type);
        System.out.println("调用函数后type的值:"+type.a);
    }
    class Mytype{
        public int a;
        public Mytype(){
            a=1;
        }
}

 
}

绿色背景的地方会报错:

“No enclosing instance of type Test is accessible. Must qualify the allocation with an enclosing instance of type Test (e.g. x.new A() where x is an instance of Test).”

此时自定义的Mytype类型属于Text的内部类

而main()方法是静态的,当

因为myType是一个动态的内部类,创建这样的对象必须有实例与之对应,程序是在静态方法中直接调用动态内部类会报这样错误。 

这样的错误好比类中的静态方法不能直接调用动态方法。可以把该内部类声明为static。或者不要在静态方法中调用。

至于为什么静态方法只能访问静态变量?我的理解是:

这与静态数据的存放位置和绑定机制有关,JAVA是动态绑定的,只有到运行的时候才真正知道要去找哪个成员的实现,
而把数据成员声明成静态的则是实现"静态绑定"的一种方法,这就是为什么声明成静态的可以提高速度的原因了.
因为静态函数也归署于静态绑定(事先就知道我要用的变量在哪),所以他只能访问静态变量!

原文地址:https://www.cnblogs.com/Yogurshine/p/3014195.html