Constructors in Java | Sololearn: Learn to code for FREE!
New course! Every coder should learn Generative AI!
Try a free lesson
+ 4

Constructors in Java

I read that constructors cannot be inherited,but i didn't understood, can anyone explain that with an example?

12th Jul 2020, 9:55 AM
Arya
1 Answer
+ 1
the constructor has the same name as the class, if class B has parent class A inherited, the constructor would have to use as B b = new A () which would be confusing. the inherited constructor would have access to class A private members from class B, which is not allowed class A { A() { System.out.println("Constructor of A: "); } A(int x) { System.out.println("Constructor of A: " +x); } } class B extends A { // B() { super(); } // added automatic as hiden // B(int x) { super(x); } // for b4 } public class Program { public static void main(String[] args) { // B b1 = new A(); //error // B b2 = new A(10); //error B b3 = new B(); //ok // B b4 = new B(20); //error } }
12th Jul 2020, 6:41 PM
zemiak