+ 4
Constructors in Java
I read that constructors cannot be inherited,but i didn't understood, can anyone explain that with an example?
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
} }