Java允许运行私有方法?有人可以解释为什么吗?

时间:2019-02-12 11:55:55

标签: java

有人问我是否可以运行私有基本功能。我告诉他,当然是不可能的(除了re俩的欺骗)。 但是,这到底是什么:

public class MyClass {
    public static void main(String args[]) {

        A a = new B();
        a.doSomething();

        B b = new B();
        b.doSomethingMore();
    }

   static class A {
        private void doSomething(){
            System.out.println("something");
        }
    }

    static class B extends A{
        public void doSomethingMore(){
            ((A)this).doSomething();
        }
    }
}

1 个答案:

答案 0 :(得分:2)

AB都是MyClass的成员,因此它们可以访问MyClass的所有私有功能,并且可以访问彼此的私有功能;并且MyClass可以访问其所有私有功能。 Java nested classes tutorial中的更多内容。

现在,如果它们嵌套类,那么自然MyClass将无法访问其私有功能,并且他们也将不会彼此访问的私人功能。例如,它将无法编译:

public class MyClass {
    public static void main(String args[]) {
        A a = new B();
        a.doSomething();            // error: doSomething() has private access in A

        B b = new B();
        b.doSomethingMore();
    }
}

class A {
    private void doSomething(){
        System.out.println("something");
    }
}

class B extends A{
    public void doSomethingMore(){
        ((A)this).doSomething();    // error: doSomething() has private access in A
    }
}
相关问题