简体   繁体   English

Java使用默认构造函数继承公共类

[英]Java inheriting public class with default constructor

I am just inheriting class ConstructorTwo in class ConstructorOne, not creating any object (explicitly atleast). 我只是继承了ConstructorOne类中的ConstructorTwo类,而不创建任何对象(明确地至少是)。 So why does the constructor in class ConstructorTwo has to be public? 那么,为什么类ConstructorTwo中的构造函数必须是公共的呢?

I am getting this error : ConstructorTwo() is not public in ConstructorTwo; 我收到此错误:ConstructorTwo()在ConstructorTwo中不是公共的; cannot be accessed from outside package 无法从外部包访问

package one;

import two.ConstructorTwo;

public class ConstructorOne extends ConstructorTwo {

    public static void main(String args[]) {

    }
}


package two;

public class ConstructorTwo {

    ConstructorTwo() { 
        super(); 
        System.out.println("Default constructor in package TWO!");
    }
}

The reason that it has to be public is because when Java calls any constructor, it has to call the superclass constructor before it calls any of the code in the subclass's constructor. 它必须公开的原因是,当Java调用任何构造函数时,它必须先调用超类构造函数,然后再调用子类的构造函数中的任何代码。 If Java cannot access the superclass constructor because of privacy errors, then it cannot execute the superclass constructor which is a required operation for calling any constructor (according to Java). 如果Java由于隐私错误而无法访问超类构造函数,则它无法执行超类构造函数,这是调用任何构造函数的必需操作(根据Java)。 This is why it has to be public. 这就是为什么它必须公开的原因。

The default constructor in class ConstructorOne calls super(); ConstructorOne的默认构造ConstructorOne调用super(); which is the default constructor in class ConstructorTwo . 这是类ConstructorTwo的默认构造ConstructorTwo When calling methods or constructors or accessing fields over package-boundries they need to be public. 在调用方法或构造函数或通过包边界访问字段时,它们必须是公共的。

The ConstructorOne class has an automatically generated public constructor, which takes no arguments, and calls super() . ConstructorOne类具有一个自动生成的公共构造函数,该构造函数不带任何参数,并调用super() Effectively, this: 实际上,这是:

public ConstructorOne() {
    super();
}

All classes implicitly have such a constructor if you don't write a constructor yourself. 如果您自己不编写构造函数,则所有类都隐式具有此类构造函数。 So there does need to be an available constructor to call in the superclass (in this case, it must be either public or protected to be accessible by a subclass in another package). 因此,确实需要在父类中调用一个可用的构造函数(在这种情况下,它必须是publicprotected才能被另一个包中的子类访问)。

When a Constructor is public, anyone can call it. 当构造函数公开时,任何人都可以调用它。 When a constructor is private, it usually means that you need to construct the object in some other manner, usually with another public static method created by the author for that purpose. 当构造函数是私有的时,通常意味着您需要以其他某种方式构造对象,通常使用作者为此目的创建的另一个公共静态方法。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM