为什么我不能只声明所有方法静态? [英] Why can't I just declare all methods static?
本文介绍了为什么我不能只声明所有方法静态?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我被这个问题质疑,为什么我不能声明所有方法都是静态的?你能在这里给我一个解释吗?谢谢。
I was being questioned by this, why can't I declare all methods static? Can you give me a piece of explanation in here? Thanks.
我相信当你创建一个静态方法时,它无法访问非静态成员吗?
I believe that when you make a method static, it cannot access non-static members?
推荐答案
静态方法无法访问实例变量。 :)
Static methods cannot access instance variables. :)
public class MyStaticExample{
private String instanceVariable = "Hello";
private static String STATIC_VARIABLE = "Hello too";
public static void staticMethod(){
System.out.println(this.instanceVariable); // this will result in a compilation error.
System.out.println(STATIC_VARIABLE); // this is ok
}
public void instanceMethod(){
System.out.println(this.instanceVariable); // this is ok
System.out.println(STATIC_VARIABLE); // this is ok
}
}
这篇关于为什么我不能只声明所有方法静态?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文