Constructor plays an important role in inheritance, constructor overriding is allowed in java. There are a set of rules and regulations while implementation constructor in inheritance. Let’s take this example:
Create a file A.java:
class A
{
A()
{
System.out.println("Constructor A");
}
}
class B extends A
{
B()
{
System.out.println("Constructor B");
}
}
public class C extends B
{
C()
{
System.out.println("Constructor C");
}
C(int x)
{
System.out.println("Parameterized Constructor C - " + x);
}
public static void main(String[] args)
{
new C(); //this is Anonymous object (Will discuss later)
new C(10);
}
}
Rule 1:
Whenever a child class constructor is executed, it has to execute the immediate parent class constructor first, then itself. If for any reason the child class is not able to execute its parent’s constructor then it cannot execute its own constructor.
In this example class A’s constructor will execute Object class constructor.
If we do not extend a class then it implicitly extend Object class.
Quick Question – why it is required to execute parent class constructor first? How it is implemented internally.
Answer – because child class does have ability to inherit all of their data members and methods but not the constructors. For example, if we have written database connection code in B class constructor, then we can never get it explicitly from C class constructor, and all database connection code will be required to be re written in C class constructor. This rule is defined for reuse of constructor.
We can call the super class constructor explicitly using super keyword, but it should be the first line in any constructor. In above example compiler automatically add super keyword in each constructor. Like this:
C()
{
super()
System.out.println("Constructor C");
}
C(int x)
{
super();
/*in this case B must have a constructor with int
argument otherwise compiler error */
System.out.println("Parameterized Constructor C - " + x);
}
Rule 2:
Compiler always adds a default constructor in each class if no any constructor is kwritten in it. In case a parameterized constructor is defined in parent class and child class is defining default constructor this compiler will throw error as it will be unable to find default constructor in parent class.
For example:
class B
{
B(int x)
{
System.out.println("Constructor B");
}
}
public class C extends B
{
C()
{
super(); //Line No 13
System.out.println("Constructor C");
}
public static void main(String[] args)
{
new C();
new C(10);
}
}
Compiler will give following error at line No 13 in above program:
Compiler will give following error at line No 13 in above program:
Error: The constructor B() is undefined
No comments:
Post a Comment