lumin0u
lumin0u

Reputation: 24

Making abstract an overridden method

Here's something I quite understand:

abstract class A {
    public void foo() {
        System.out.println("a");
    }
}

abstract class B extends A {
    @Override
    public abstract void foo();
    
    public void bar() {
        super.foo();
        foo();
    }
}

class C extends B {
    @Override
    public void foo() {
        System.out.println("c");
    }
}
public static void main(String[] args) {
    new C().foo();
    new C().bar();
}

new C().foo() prints c to the console, while new C().bar() prints a then c.

Calling super.foo() is illegal in the #foo() implementation of the C class.

I don't have a clear question, but if anyone could give a complete explanation of what is going on with the foo method, it may be interesting I think.

Upvotes: 0

Views: 42

Answers (1)

Zychoo
Zychoo

Reputation: 625

A is super class for B, so calling super.foo() inside B calls method defined in A, and calling foo() inside the same class will invoke its own implementation that should be delivered by any subclass.

You cannot use super.foo() within C class because it is defined as abstract in B and cannot be invoked directly.

Upvotes: 1

Related Questions