Access Modifiers

Public members

Private members

1. Can private methods be overriden?

Reference: from a Javaranch question here http://saloon.javaranch.com/cgi-bin/ubb/ultimatebb.cgi?ubb=get_topic&f=33&t=025061

class Super{
   private void Hello(){
    System.out.println("Iam in Super()");
   }  
}
class Sub extends Super{
   private void Hello(){
      System.out.println("Iam in Sub()");
   }
}
public class Checking{
   public static void main(String[] args)
   {
      Super s = new Sub();
      Sub s1 = new Sub();
 
      s.Hello();//iam getting error why ?
      s1.Hello();//this is Correct
   }
}

Answer from I Wayan Saryada:
Both line in your main method should give a compile time error because you cannot call a private method from outside its class.

For other notes, the Sub class is not overriding the Super class Hello method because we cannot override a private method.

Answer from Jesper Young:
The variable 's' is of type Super. That means that if you call a method on it, it will only look in class Super, even when 's' really refers to a Sub object. Because the method is private in class Super, you can't call it on s.

Also, private methods cannot be overridden. A private method is only visible in the class in which it is declared. It is not visible in subclasses. The subclass doesn't know what private methods exist in its superclass, so it can't override private methods in the superclass. You should see the hello() method in class Sub as a new method that's totally unrelated to the hello() method in class Super.

Protected members

Default members

Unless otherwise stated, the content of this page is licensed under Creative Commons Attribution-Share Alike 2.5 License.