Why can't I call a method I define in a field?

时间:2015-06-15 14:36:30

标签: java oop methods

Consider the following code.

B.java

public class B {

    void foo() {
        System.out.println("foo");
    }

}

A.java

public class A {

    B b = new B() {
        void lorem() {
            System.out.println("Lorem");
        }
    };

    void bar() {
        // Why can't I call b.lorem() here?
        b.foo();
    }

}

Why can't I call b.lorem() in bar()?

1 个答案:

答案 0 :(得分:3)

lorem is a method of an anonymous sub-class of B. Therefore you can't call it by using a reference of class B, and since it's anonymous, you can't cast b to a type that contains lorem.

相关问题