Question

This is a code from SCJP 6 book :

    private final void flipper() {
    System.out.println("Clidder");
  }
}

public class Clidlet extends Clidder {

  public final void flipper() {
    System.out.println("Clidlet");
  }

  public static void main(String[] args) {
    new Clidlet().flipper();
  }
}

in here method private final void flipper() in super class is a final method and we know that They can not be over ridden by their subclass because its final.

In Clidlet class there is a method method in same name public final void flipper() difference is this one is public. So my question is how this access specifier involving the overriding here? Because of this super class method is private can we use it on subclass with the same name , same arguments , same return type but not as overriding??

Was it helpful?

Solution

It's not overriding the method. Private methods are not inherited and are not accessible by or visible to subclasses. Having both private and final on a method is rather silly.

Your Clidlet class does not actually override that method from Clidder, it simply defines a new method named flipper() that is unrelated to the one in Clidder.

This is precisely why the @Override keyword exists. Use it, and it will prevent you from making subtle errors like this, e.g. the following code would fail to compile since flipper() isn't actually overriding anything:

public class Clidlet extends Clidder {

  @Override public final void flipper() {
    System.out.println("Clidlet");
  }

  public static void main(String[] args) {
    new Clidlet().flipper();
  }

}

That's a very poor example for them to have put in that book, unless it's specifically an example of subclasses not having access to base private methods.

OTHER TIPS

This is not an actual override, the child class is simply declaring a new method that happens to have the same name; you can only do this because the method in the parent is private, meaning the child class cannot see it and thus there will be no confusion for the compiler.

I have found a more detailed answer here.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top