Understanding Constructor and Method Overriding in Java - BunksAllowed

BunksAllowed is an effort to facilitate Self Learning process through the provision of quality tutorials.

Random Posts

Understanding Constructor and Method Overriding in Java

Share This


Let us define a superclass Parent.java, a child class Child.java, and a  class TestMain.java to test the program as shown below.

Code of Parent.java
package com.bunks; public class Parent { public Parent() { System.out.println(this.getClass()); System.out.println("I am in parent constructor!"); testMethod(); this.testMethod(); } public void testMethod() { System.out.println("I am in Parent!"); } }

Code of Child.java
package com.bunks; public class Child extends Parent { public Child() { super(); System.out.println(this.getClass()); System.out.println("I am in child constructor!"); super.testMethod(); this.testMethod(); } public void testMethod() { System.out.println("I am in child!"); } }


Code of TestMain.java
package com.bunks; public class Testmain { public static void main(String[] args) { Child child = new Child(); child.testMethod(); Parent p = new Child(); p.testMethod(); } }


If we create an object of the Child class, the constructor of the child class is called, which in turn calls the constructor of the superclass. In this example, the testMethod() is defined in the superclass and is overridden in the child class. Thus, if we call testMethod() using a child class reference, the overridden method is called.

Note that, if testMethod() is called from the child class constructor or from the parent class constructor, in both of these contexts, the overridden method is called. If the method is called from a superclass or child class constructor, the method is called by the current object reference this (whether it's mentioned or not). Thus to call the superclass method, you have to explicitly call the method using superclass reference super from the child class. 

As we are demanding that the reference this in superclass refers to the same object of the child class, we have added System.out.println(this.getClass()); in both of the constructors.

Even if, you access the child class object using the parent class reference, the child class method is called, instead of the parent class method.

Check the output.   

Happy Exploring!

No comments:

Post a Comment