-2

why should we widen the accessibility of overridden methods ? If the super class has a protected method and subclass has same method with public. Why should happen?

Chandra Sekhar
  • 18,914
  • 16
  • 84
  • 125
Hari
  • 397
  • 1
  • 9
  • 23
  • 1
    Private methods are not available in subclasses and are not exposed to the clients. A public method in a subclass is an entirely different method. – Alexander Pavlov Apr 09 '12 at 13:16
  • Possible duplicate - http://stackoverflow.com/questions/9330001/what-are-the-benefits-of-being-able-to-change-the-access-modifier-of-an-overridd – mre Apr 09 '12 at 13:16

3 Answers3

3

It's a different method! Subclasses don't inherit private methods! So you're not "overriding" at all. You are simply DEFINING a method with the same name as the private method in the superclass.

 class A
   {
      private void myMethod() { }
   }

 class B extends A
   {
     public void myMethod() { } // a completely different method. Has nothing to do with the above method. It is not an override. 
   }
CodeBlue
  • 14,631
  • 33
  • 94
  • 132
1

Because in an object hierarchy, JVM will always run the Overriden method. If your overriden method is not accessible, then it is useless.

public class A{
    void A(){}
}
public class B extends A{
    private void A(){} //this makes no sence and its impossible
    PSV main(String ..){
        A a = new B();
        a.A(); //error as JVM cannot call overriden method which is private.
    }
}
Chandra Sekhar
  • 18,914
  • 16
  • 84
  • 125
1

Methods declared as private or static can not be overridden!

Annotation @Override indicates that a method declaration is intended to override a method declaration in a superclass. If a method is annotated with this annotation type but does not override a superclass method, compilers are required to generate an error message.

Use it every time you override a method for two benefits. This way, if you make a common mistake of misspelling a method name or not correctly matching the parameters, you will be warned that you method does not actually override as you think it does. Secondly, it makes your code easier to understand because it is more obvious when methods are overwritten. And in Java 1.6 you can use it to mark when a method implements an interface for the same benefits.

Michael
  • 1,152
  • 6
  • 19
  • 36