Java中静态方法不能调用非静态方法报错Cannot make a static reference to the non-static field

public class HelloWorld {
int a = 1;
public static void main(String[] args) {
System.out.println(a);
}
}

编译报错:
Exception in thread “main” java.lang.Error: Unresolved compilation problem:
Cannot make a static reference to the non-static field a

at helloworld/helloworld.HelloWorld.main(HelloWorld.java:6)

因为我们知道静态的方法可以在没有创建实例时使用,而申明为非静态的成员变量是一个对象属性,它只有在对象存在时引用,因此如果在对象未创建实例时我们在静态方法中调用了非静态成员方法自然是非法的,所以编译器会在这种时候给各错误.

简单说来,静态方法可以不用创建对象就调用,非静态方法必须有了对象的实例才能调用.因此想在静态方法中引用非静态方法是不可能的,因为它究竟引用的是哪个对象的非静态方法呢?编译器不可能给出答案,因为没有对象啊,所以要报错.

两种解决办法:
1.将非静态的成员变量声明为静态
public class HelloWorld {
static int a = 1;
public static void main(String[] args) {
System.out.println(a);
}
}

2.先创建对象然后再引用
public class HelloWorld {
int a = 1;
public static void main(String[] args) {
HelloWorld hw = new HelloWorld();
System.out.println(hw.a);
}
}

  • 3
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值