[Solved] Inheritance and constructors in Java


First of all, the code you posted is not valid Java. It is important that you post working code, otherwise we can’t be sure about what you are asking.

  1. Does the statement super(1,2,3) in the class B create a private fields same as the private fields in the class A? Or is it illegal to use this statement because B cant inherit the private fields of A?

Assuming you put the statement in a constructor instead of at class level, which is illegal, then no, that will not automatically create fields in class B. It just calls the constructor in the superclass A that takes three int arguments and initializes the fields in the superclass part of the object.

  1. And we suppose that we didn’t use the super constructor in the class B then normally the computer will call the default constructor of the class A. We know that private fields are not inherited in Java so what will the default constructor initialize in this state ?

Since there is no default (i.e. no-arguments) constructor in class A, you would get a compiler error – the compiler would complain that there is no appropriate constructor in class A.

Java only automatically adds a no-arguments constructor to a class if you do not specify a constructor at all in the class. Since class A already has a constructor, Java is not automatically going to add a no-arguments constructor.

solved Inheritance and constructors in Java