Java实例说明 静态方法和非静态方法的区别

代码:

public class OuterMyTest { private static int a ; private int b ; public OuterMyTest(){ a += 1; b += 1; //System.out.println( "a = " + a + "; b = " + b ); } public void getFun(){ System.out.println(b); } public static void main(String[] args) { int c =1; System.out.println(c); OuterMyTest a1 = new OuterMyTest(); OuterMyTest a2 = new OuterMyTest(); System.out.println(a); getFun();//报错

OuterMyTest.getFun();//报错

a1.getFun(); //通过 } }

编译报错:Cannot make a static reference to the non-static method getFun() from the type OuterMyTest

改进:a1.getFun();

或者public static void getFun(){ System.out.println(b); }

原因:

静态方法只能访问静态成员,因为非静态方法的调用要先创建对象,在调用静态方法时可能对象并没有被初始化。

OuterMyTest是一个类名,用类名只能调静态方法,getFun是非静态方法,所以要在对象上面调用,先要获取一个
OuterMyTest类的对象 OuterMyTest a1 = new OuterMyTest();然后再调用a1.getFun();类的对象 OuterMyTest a1 = new OuterMyTest();然后再调用a1.getFun();
经验分享 程序员 微信小程序 职场和发展