2

im currently preparing for a job interview, and there is a question really makes me confused. people say that in java constructor can't be inherited, but code like this

public class childclass extends parentclass{

public childclass(){
    super();
    System.out.println("child");
}

public static void main(String[] args) {
    childclass cc = new childclass();
}}

doesn't super() mean childclass inherited parentclass's constructor?

Chase
  • 195
  • 1
  • 1
  • 10

4 Answers4

0

If a constructor does not explicitly invoke a superclass constructor, the Java compiler automatically inserts a call to the no-argument constructor of the superclass. If the super class does not have a no-argument constructor, you will get a compile-time error. Object does have such a constructor, so if Object is the only superclass, there is no problem.

According to super docs

Abdelhak
  • 8,299
  • 4
  • 22
  • 36
0

Constructors are not members, so they are not inherited by subclasses, but the constructor of the superclass can be invoked from the subclass.

Youssef NAIT
  • 1,362
  • 11
  • 27
  • 1
    A constructor of the superclass *must* be invoked from the subclass' constructor (although that can be implicitly done, if the superclass has a zero-arg constructor). – Andy Turner Feb 24 '16 at 08:35
  • _Suppose constructors were inherited... then because every class eventually derives from Object, every class would end up with a parameterless constructor. That's a bad idea._ check out this [post](http://stackoverflow.com/questions/1644317/java-constructor-inheritance) for more details. – Youssef NAIT Feb 24 '16 at 08:43
0

Well it can be a bit confusing. However you are not inheriting the parent constructor, instead you are using it.

Specialized classes inherits all members of parent class, but not constructors, although specialized class must use it, by means of super.

malaguna
  • 4,183
  • 1
  • 17
  • 33
0

I think, this question was answered in https://stackoverflow.com/a/18147860/5964970. Inheritance means that the name of a method (and constructor) in a subclass is the same as in the parent class. But constructor names in subclasses are equal to the class name of the subclass and not equal to the constructor name of the parent class.

Community
  • 1
  • 1