2014-09-04 95 views
-2
public class B extends A{ 
    public int g(){ 
     int x = super.x; 
     int y = super.getOne(); 
     return x+y; 
    } 
    public static void main(String args[]){ 
     System.out.println(g()); 
    } 
} 

为什么我收到错误(在印刷线的左侧):静态和非静态误差

不能让)从静态参考非静态方法克( B型

+0

由于无法对类型B的非静态方法g()进行静态引用,因此会出现该错误。 – 2014-09-04 16:01:59

+0

为B创建对象 – 2014-09-04 16:02:42

回答

0

因为您无法访问静态上下文中的非静态方法 - 在这种情况下是main方法。

这将工作:

public static void main(String args[]){ 
    B b = new B(); 
    System.out.println(b.g()); 
} 

你有静态的主要方法创建B级的一个实例,然后调用g();

0

你不能直接调用这样的非静态方法,你必须创建一个超出类B的对象,然后使用该对象的方法g()。