【问题标题】:java, inheritance — private field in parent is accessed through a public method in childjava,继承——父类中的私有字段通过子类中的公共方法访问
【发布时间】:2014-06-01 11:08:41
【问题描述】:

所以,一个朋友给我发了这段代码,说编译成功,返回 42。 但是,麻烦的是“返回” 42 的父类中的方法是私有的,而被调用的方法是在子类中的,它是公共的。那么,谁能说出这是为什么以及如何工作的?

static class A {
    private int f() {
        return 42;
    }
}

static class B extends A {
    public int f2() {
        return super.f();
    }
}

public static void main(String[] args) {
    System.out.print(new B().f2());

}

它返回 42。

我试图摆脱静电,并且

class A {
    private int f() {
        return 42;
    }
}

class B extends A {
    public int f2() {
        return super.f();
    }
}

public static void main(String[] args) {
    Main m= new Main();
    B b= m.new B();
    System.out.print(b.f2());

}

它仍然返回 42。

【问题讨论】:

    标签: java inheritance private public


    【解决方案1】:

    由于两个类(AB)都嵌套在 Main 中,因此它们可以访问 private int f() 方法。

    如果你在顶级类中提取AB的源代码,就不会发生这种情况,你会编译失败。

    【讨论】:

      【解决方案2】:

      私有的要点是“外部”类不应该能够看到私有变量。但是 A 和 B 都是同一个类的一部分,或者相互嵌套,因此它们可以访问彼此的私有成员。

      所以这会起作用:

      public class A {
      
         private void a() {
           int bVal = this.new B().val;   //! Accessing B private
         }
      
         class B {
            A a = new A();
            private int val = 10;
            public void b() {
               a.a();      // !! Accessing A private
            }
      }
      

      但是,即使 A 和 B 在同一个 文件 中但不在彼此内,这也会失败:

      class A {
          private void a() {}
      }
      
      class B extends A {
         A a = new A();
         public void b() {
            a.a();  // can't see even if B extends A
         }
      }
      

      【讨论】:

        【解决方案3】:

        这是因为 A 类和 B 类都嵌套在另一个类中,即两个类都是另一个相同类的内部类(或“部分”)。由于它们(数据成员和方法)基本上是外部类的成员,因此即使是私有的,它们也可以在其他内部类中访问。

        Java 允许我们嵌套类,如果您不了解嵌套类,请先阅读以下内容:
        http://docs.oracle.com/javase/tutorial/java/javaOO/nested.html

        class Outer{
        
        
        class A {
            private int f() {
                return 42;
            }//Method f() is a private member of A and accessible by Outer
        }
        
        class B extends A {
            public int f2() {
                return super.f(); 
            }//As class B is inner class of Outer it can access members of outer,thus indirectly member of A 
        }
        
        public static void main(String[] args) {
            System.out.print(new B().f2());
        
        }
        
        }
        

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 2011-04-03
          • 2015-03-07
          • 1970-01-01
          • 1970-01-01
          • 2012-11-15
          • 1970-01-01
          • 1970-01-01
          • 2014-11-24
          相关资源
          最近更新 更多