Constructors in case of inheritance
- When a program creates a subclass object, the subclass constructor immediately calls the superclass constructor (explicitly, via super, or implicitly).
- The superclass constructor’s body executes to initialize the superclass’s instance variables that are part of the subclass object, then the subclass constructor’s body executes to initialize the subclass-only instance variables.(cont…)
- Java ensures that even if a constructor does not assign a value to an instance variable, the variable is still initialized to its default value (e.g., 0 for primitive numeric types, false for booleans, null for references).
- Java can implicitly call only the no argument constructor of the super class.
The following example illustrates the calling order of the constructors in case of inheritance when an object for subclass is created.
- /* Constructor calling */
- class one //Super class
- {
- one()
- {
- System.out.println("Inside the constructor of class one");
- }
- }
-
- class two extends one //Sub class
- {
- two()
- {
- System.out.println("Inside the constructor of class two");
- }
- }
-
- /* Main class */
- class callconst
- {
- public static void main(String args[])
- {
- System.out.println("Creating instance of class two\n");
- two t=new two(); //creating instance of class two
- }
- }
D:\Java>javac callconst.java
D:\Java>java callconst Creating instance of class two
Inside the constructor of class one Inside the constructor of class two
0 comments
Post a Comment