Can a private method in super class be overriden in the sub-class?

No, a private method cannot be overridden since it is not visible from any other class. If we do this than its a new method for your subclass that has no relation to the superclass method. One way to look at it is to ask yourself whether it would be legal to write super.func() in the Derived class. Ofcourse, it will give compile time error.

class Base {
      private void func(){
            System.out.println("In base func method");
      };
      public void func2() {
          System.out.println("func2");
          func();
      }
}

class Derived extends Base {
      public void func(){   //  Is this an overriding method?
            System.out.println("In Derived Class func method");
      }
}

class InheritDemo {
      public static void main(String [] args) {
            Derived D = new Derived();
            D.func2();
      }
}

It will print:

func2
In base func method

When you change func() in Base to public, then it will be an override, and the output will change to:

func2
In Derived Class func method

Leave a Reply

Your email address will not be published. Required fields are marked *

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>

Post Navigation