user9432743
user9432743

Reputation:

Accessing abstract class method

I have three different classes:

1-)

abstract class A {
abstract void one();
void two(){
    System.out.println("two");
one();
}
abstract void three();
 }

2-)

abstract class B extends A {
void one() {
    System.out.println("one");
    three();//I think this method has to run
}

void three() {
    System.out.println("3");//That
}
}

3-)

public class C extends B {
void three(){
    System.out.println("three");
}

}

in the Main method

public static void main(String [] args){
C c=new C();
c.one();
c.two();
c.three();
}

Output :

one
three
two
one
three
three

But I think in second code one() method have to run its three method and it has to show "3" instead of "three" but this code runs three in C class.

Upvotes: 1

Views: 62

Answers (3)

Gyan
Gyan

Reputation: 1

Overriding in java always works based on the target object in reference ‘c’. So firstly it will look up in C class for any available overridden version of three() method, otherwise, subsequent parent class version will get executed.

Upvotes: 0

Mureinik
Mureinik

Reputation: 310993

The three() method is overridden in C. Since c holds an instance of C, that's the output you see.

Upvotes: 1

user3483645
user3483645

Reputation: 11

three() method is overridden both in B and C class

Since c is an instance of C class, any reference to three() method with c object will invoke the three() implementation in C class

Upvotes: 1

Related Questions