简体   繁体   中英

Java inheriting public class with default constructor

I am just inheriting class ConstructorTwo in class ConstructorOne, not creating any object (explicitly atleast). So why does the constructor in class ConstructorTwo has to be public?

I am getting this error : ConstructorTwo() is not public in 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. 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). This is why it has to be public.

The default constructor in class ConstructorOne calls super(); which is the default constructor in class 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() . 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).

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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