java 中 Cannot make a static reference to the non-static 解决方法

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

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)。

  1. java中不能将方法体内的局部变量声明为static
  2. main()函数是静态的,没有返回值,形参为数组。
  3. 非静态成员的可以随便调用静态成员

原来静态这么反人类,那要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);
    }
}
  • 86
    点赞
  • 163
    收藏
    觉得还不错? 一键收藏
  • 10
    评论
Java,当我们尝试在静态上下文引用非静态方法时,就会出现"Cannot make a static reference to the non-static method"的错误。这个错误通常发生在以下两种情况下: 1. 在静态方法引用非静态方法:静态方法是属于类的,而非静态方法是属于对象的。因此,在静态方法无法直接引用非静态方法,因为没有对象实例来调用非静态方法。 2. 在静态方法引用非静态成员变量:同样地,静态方法是属于类的,而非静态成员变量是属于对象的。在静态方法无法直接引用非静态成员变量,因为没有对象实例来访问非静态成员变量。 解决这个问题的方法有两种: 1. 创建对象实例:如果你需要在静态方法引用非静态方法或非静态成员变量,你可以先创建一个对象实例,然后通过该对象实例来调用非静态方法或访问非静态成员变量。 2. 将非静态方法或非静态成员变量改为静态:如果你确定在静态上下文需要引用某个方法或成员变量,你可以将其改为静态的。这样就可以直接通过类名来引用,而不需要创建对象实例。 下面是一个示例代码,演示了如何解决"Cannot make a static reference to the non-static method"错误: ```java public class Test { private int num; public static void main(String[] args) { // 创建对象实例 Test test = new Test(); test.nonStaticMethod(); // 调用非静态方法 // 或者将非静态方法改为静态方法 staticMethod(); } public void nonStaticMethod() { System.out.println("This is a non-static method."); } public static void staticMethod() { System.out.println("This is a static method."); } } ```

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 10
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值