"静态方法里仅仅能调用静态变量和静态方法"具体解释

静态方法里能够调用静态方法和静态变量,同一时候也能调用非静态方法和非静态变量。

public class Test {

public Test() {};
public Test(int i) {this.n = i;}

public static int m = 5;
public int n = 10;

public void fun1() {System.out.println("非静态方法fun1");}
public static void fun2() {System.out.println("静态方法fun2");}

//測试“静态方法里仅仅能调用静态变量和静态方法”详细是什么意思
public static void main(String[] args) {
 //调用静态方法不会报错
 //fun2();

 //调用静态变量不会报错
 System.out.println(m);

 //无法从静态上下文中引用非静态方法fun1()
 //fun1();

 //无法从静态上下文中引用非静态变量n
 //System.out.println(n);

 //能够在静态方法中new对象,调用到了非静态方法的构造方法。无论是否默认构造方法。下列代码均能正确运行。故觉得:“编译阶段,编译器不会检查静态方法中牵扯到 详细对象以及对象的相关操作”。如此,也提供了静态方法中訪问非静态方法和非静态属性的解决方式。
 //Test t = new Test(8);
 //t.fun2();
 //t.fun1();
 //System.out.println(t.m);	
 //System.out.println(t.n);
 
}
}


posted @ 2019-05-01 19:00  ldxsuanfa  阅读(972)  评论(0编辑  收藏  举报