无法弄清楚这个简单的Java代码中的错误

时间:2012-12-01 05:23:49

标签: java

public class Test {
    class Foo {
        int frob() {
            return 7;
        }
    }

    class Bar extends Foo {
        @Override
        int frob() {
            return 8;
        }
    }

    class Baz extends Foo {
        @Override
        int frob() {
            return 9;
        }
    }

    public static int quux(Bar b) {
        return b.frob();
    }

    public static void main(String[] args) {
        System.out.println(quux(new Bar()));//this line gives non-static variable this cannot be referenced from a static context
    }

}

3 个答案:

答案 0 :(得分:3)

您可以通过将嵌套类声明为 static 来解决此问题,或者通过在 Test 的实例的上下文中实例化 Bar 来解决此问题。 / p>

失败是因为(非静态) Bar 必须在现有 Test 类实例的上下文中实例化;因为 main 是静态的,所以没有这样的野兽。

答案 1 :(得分:3)

public static void main(String[] args) {
    Test test = new Test();
    System.out.println(quux(test.new Bar()));
}

答案 2 :(得分:2)

非静态内部类具有对封闭类实例的隐藏引用。这意味着您必须具有封闭类的实例才能创建内部类。您还必须使用一个特殊的“新”函数来正确初始化对封闭类的隐藏引用。例如,

   class Outer{   
        class Inner{
           public Inner() {
               System.out.println("Hello there.");
           }
        }

        public static void main(String args[]) {
            Outer o = new Outer();     
            Outer.Inner i = o.new Inner();
        }
    }
相关问题