Sajad
Sajad

Reputation: 2363

Override method in inheritance

My code:

public class PrivateOverride {

private void f() {
    System.out.println("private f()");
}

public static void main(String[] args) {
    PrivateOverride po = new derived();
    po.f();
   }
}

class derived extends PrivateOverride {

public void f() {
    System.out.println("public f()");
    }
}

Output: private f()

Why?

Upvotes: 3

Views: 81

Answers (4)

kiruwka
kiruwka

Reputation: 9450

Because derived#f() does not override parent's class private f() method.

You could confirm it by adding @Override annotation to f() method in derived class and see that it won't compile.

Extra tips :
To override method f(), it should be inherited from parent's class, i.e. visible in your subclass, which is never the case for private methods.

Additional rules for correct method overriding are summarized in this table.

Upvotes: 7

Meet
Meet

Reputation: 242

Because Private method can't be Inherited in subclass so it can't be overridden.

Upvotes: 0

BobTheBuilder
BobTheBuilder

Reputation: 19304

Method f in PrivateOverride is declared as private. That means that it isn't overridden in derived class.

That's why you should use @Override annotation. In that case it would show you the error.

Upvotes: 2

Eng.Fouad
Eng.Fouad

Reputation: 117665

derived cannot see PrivateOverride's f() because it's private, and hence that is not an overriding, it's definition of a new method. It's always recommended to add the annotation @Override on the overridden method just to avoid such hidden problems.

Upvotes: 2

Related Questions