OOPS Concepts Calling a Parent Class Not a Child

I have a parent class.

import java.util.HashMap; import java.util.Map; public class Parent { Map<String,String> map = new HashMap<String, String>(); public void process(){ System.out.println("parent"); this.checkFunction(); } protected void checkFunction(){ System.out.println("parentC"); System.out.println(map); } public void init(){ (map).put("parent","b"); } } 

Now, as expected, I have a child class.

 import java.util.HashMap; import java.util.Map; public class Child extends Parent { Map<String,String> map = new HashMap<String, String>(); public void checkFunction(){ System.out.println(map); System.out.println("ChildC"); } public void process(){ super.process(); System.out.println("Child"); } public void init(){ super.init(); (map).put("child","b"); } } 

To check what I want, I have a main class.

 public class test { /** * @param args */ public static void main(String[] args) { // TODO Auto-generated method stub Child a = new Child(); a.init(); a.process(); Parent p = a; p.checkFunction(); } } 

When I call a.process (), I assume that it should call child.process (), which will be in the super.process () callback. So far, so good. In the parent process (), it should call checkFunction ().

Now, according to my understanding, it should call checkFunction () of the Parent class. Why does it call Child checkFunction ()?

My conclusion is similar to this

 parent {child=b} ChildC Child {child=b} ChildC 

I expect it to be

 parent parentC {parent=b} Child {child=b} ChildC 
+4
source share
1 answer

This is because you redefined checkFunction in the child class. therefore, the instance of the child will call the child checkFunction, even if the call is from the parent class.

If you want to call the parent control function from the child instance, you need to call super.checkFunction () in the child class. The super keyword essentially β€œmoves” the inheritance chain.

A detailed description of the super keyword can be found here.

+5
source

All Articles