TwistAndShutter
TwistAndShutter

Reputation: 239

When overriding method X, will a call to X from an inherited method use the overriding or the overridden implementation of X?

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

Answers (3)

chenop
chenop

Reputation: 5143

Your code is correct but pay attention to the following:

  1. First of all you didn't specify exposure level (private, protected etc.), in that case your method default exposure level is "package protected".
  2. 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

SebastianGreen
SebastianGreen

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

Rinke
Rinke

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.printlns will prove it.

Upvotes: 2

Related Questions