java 中的 Cannot make a static reference to the non-static method


原文: https://blog.csdn.net/q610376681/article/details/49359819

今天敲代码的时候遇到了这个问题,大体这个问题可以简化成这样;

public class Test1 {
    public String get()
    {
        return "123";
    }
    public static void main(String[] args)
    {
        String string =get();
    }


显示 
Cannot make a static reference to the non-static method get() from the type Test1

好吧,我决定改成这样

public class Test1 {
    public String get()
    {
        return "123";
    }
    public static void main(String[] args)
    {
         static String string =get();
    }
}


可是还是错的。。。。

翻了一下java书才知道

1.java中 静态方法不可以直接调用非静态方法和成员,也不能使用this关键字(这就是这个问题的原因,我用静态的main方法调用了非静态的的get方法)。

原因解释:类中静态的方法或者属性,本质上来讲并不是该类的成员,在java虚拟机装在类的时候,这些静态的东西已经有了对象,它只是在这个类中”寄居”,不需要通过类的构造器(构造函数)类实现实例化;而非静态的属性或者方法,在类的装载是并没有存在,需在执行了该类的构造函数后才可依赖该类的实例对象存在。所以在静态方法中调用非静态方法时,编译器会报错(Cannot make a static reference to the non-static method func() from the type A)。

java中不能将方法体内的局部变量声明为static
main()函数是静态的,没有返回值,形参为数组。
非静态成员的可以随便调用静态成员
原来静态这么反人类,那要this的干什么呢? 
大概就是为了使多个类共享一个数据。

大概修改了一下,将函数变为static,将变量声明为全局静态的

方法一:

public class Test1 {
    static String  string;
    public static String get()
    {
        return "123";
    }
    public static void main(String[] args)
    {
         string =get();
         System.out.print(string);
    }
}


方法二

public class Test1 {
    public  String get() {
        return "123";
    }
    public static void main(String[] args) {
        Test1 c = new Test1();
        String string = c.get();
        System.out.print(string);
    }
}


 

猜你喜欢

转载自blog.csdn.net/guozuofeng/article/details/84453358
今日推荐