OOPS concepts Call function of Parent class not 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 test 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 it should call child.process() which will in return call super.process(). So far so good. In Parent's process(), it should call check开发者_如何学JAVAFunction().
Now, as per my understanding it should call checkFunction() of Parent class. Why is it calling Child's checkFunction()?
My output is something like this
parent
{child=b}
ChildC
Child
{child=b}
ChildC
I expect it to be
parent
parentC
{parent=b}
Child
{child=b}
ChildC
This is because you have overridden checkFunction in the child class. therefore an instance of child will call the child checkFunction even if the call is from parent class.
If you want to call the parents checkfunction from an instance of the child you need to call super.checkFunction() in the child class. The super keyword essentially "moves up" the inheritance chain.
A detailed description of the super keyword can be found here
精彩评论