Reputation: 239
I have this two java classes with this methods:
class A {
void m1 () {
...
}
void m2 () {
...
m1();
...
}
}
class B extends A {
@Ovveride
void m1() {
...
}
void m3() {
m2();
}
}
What I'm not sure is if the m1()
called inside m2()
called inside m3()
is the new implementation defined inside B or the one in A.
I would wish to call the m2()
method defined in A BUT using the m1()
implementation defined in B. My code is correct?
Upvotes: 1
Views: 89
Reputation: 5143
Your code is correct but pay attention to the following:
you need to instantiate B in order to use it's override methods:
A obj = new B();
obj.m3();
Now your m1 method of obj will actually linked to B.m1()
Upvotes: 0
Reputation: 134
Class A:
public class A {
public void m1(){
System.out.println("Method1 from class A");
}
public void m2(){
System.out.println("Method2 from class A");
m1();
}
}
Class B:
public class B extends A{
@Override
public void m1(){
System.out.println("Method1 from class B");
}
public void m3(){
m2();
}
}
Main :
public class TestAB {
public static void main(String[] args) {
A a=new A();
B b=new B();
a.m1();a.m2();
System.out.println();
b.m1();
b.m3();
}
}
Result:
Method1 from class A Method2 from class A Method1 from class A
Method1 from class B Method2 from class A Method1 from class B
Upvotes: 0
Reputation: 6332
This is exactly what will happen. Class B overrides method m1 and inherits m2. Inside m2 there is a call to m1 on the current object. (Remeber: "m1();" is short for "this.m1();".) Since m1 is overridden on instances of B, the overridden method will be called.
But don't take my word for it, try it yourself! Putting in one or two simple System.out.println
s will prove it.
Upvotes: 2