【问题标题】:Why am I able to inherit & call a private constructor in a subclass?为什么我能够在子类中继承和调用私有构造函数?
【发布时间】:2016-08-14 18:37:42
【问题描述】:

我读到不可能从构造函数是私有的类创建子类,但奇怪的是我能够做到,这个 sn-p 还有更多的东西吗?

请有人提供一个易于理解且令人满意的解释。

public class app {

    public static void main(String[] args) {
        app ref = new app();
        myInheritedClass myVal = ref.new myInheritedClass(10);
        myVal.show();

    }

    int myValue = 100;

    class myClass {
        int data;

        private myClass(int data) {
            this.data = data;
        }

    }

    class myInheritedClass extends myClass {
        public myInheritedClass(int data) {
            super(data);
        }

        public void show() {
            System.out.println(data);
        }

    }
}

我在https://www.compilejava.net/ 上运行了这个 sn-p,输出为 10。

【问题讨论】:

  • 为什么它不能工作?你在哪里读过帽子?子类有一个公共构造函数——这使得它可以访问
  • OP - 请注意,Java 类名通常以大写字母开头。
  • 因为这些是内部类,它们都在同一个(外部)类中。
  • 使用编码约定可以让其他人更容易阅读您的代码。如果您关心您的代码被阅读或看起来很专业,请使用编码约定。
  • 链接的重复不是同一个问题

标签: java subclass private-constructor


【解决方案1】:

因为您的类都是 嵌套类(在您的情况下,特别是 inner 类),这意味着它们都是包含类的一部分,因此可以访问到包含类中的所有私有事物,包括彼此的私有位。

如果它们不是嵌套类,您将无法在子类中访问超类的私有构造函数。

有关嵌套类的更多信息,请参见 Oracle Java 网站上的 nested class tutorial

这样可以编译,因为 AB 是内部类,它们是嵌套类 (live copy):

class Example
{
    public static void main (String[] args) throws java.lang.Exception
    {
        System.out.println("Ran at " + new java.util.Date());
    }

    class A {
        private A() {
        }
    }
    class B extends A {
        private B() {
            super();
        }
    }
}

这可以编译,因为AB静态嵌套 类(live copy):

class Example
{
    public static void main (String[] args) throws java.lang.Exception
    {
        System.out.println("Ran at " + new java.util.Date());
    }

    static class A {
        private A() {
        }
    }
    static class B extends A {
        private B() {
            super();
        }
    }
}

这个无法编译因为A的构造函数是私有的; B 无法访问它(在这种情况下我真的不需要Example,但我已经将它包含在上面的两个中,所以对于上下文......)(live copy):

class Example
{
    public static void main (String[] args) throws java.lang.Exception
    {
        System.out.println("Ran at " + new java.util.Date());
    }
}
class A {
    private A() {
    }
}
class B extends A {
    private B() {
        super();    // COMPILATION FAILS HERE
    }
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2011-10-30
    • 1970-01-01
    • 1970-01-01
    • 2015-10-07
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多