Reputation: 1685
Will Parent.parentMethod2
or Child.parentMethod2
be invoked when running Child.childMethod1
?
public class Parent
{
public void parentMethod1()
{
parentMethod2();
}
public void parentMethod2()
{
//do something
}
}
public class Child extends Parent
{
public void childMehod1()
{
parentMethod1();
}
@Override
public void parentMethod2()
{
//do something else
}
}
Upvotes: 0
Views: 79
Reputation: 107
The child method will be called (i.e. the overridden parentMethod2). This is the "normal" way inheritance works in java - your object is a child, so it will run the child's methods when they are available. it does not matter that we call parentMethod2 from parentMethod1, which is not overridden. the instance running the method is still a child
Upvotes: 2
Reputation: 10553
remember one thing
public class Parent
{
public void parentMethod1()
{
this.parentMethod2(); //I have added 'this' here, ('this' is implicit)
}
}
so 'this' is currently executing object which is child object. So child method will be called.
Upvotes: 1
Reputation: 7024
Child.childMehod1()
will call Child.parentMethod2()
. meaning, your "//do something else" code will be executed.
Upvotes: 1