Rules of Access Specifiers in Method Overriding

Rules of Access Specifiers in Method Overriding


Access Specifiers Method Overriding: The only rule says:

"The subclass overridden method cannot have weaker access than super class method".

Let us see the above rule practically in Access Specifiers Method Overriding.


Access Specifiers Method Overriding
Output screen of Access Specifiers Method Overriding

Protected display() method of Test class is overridden by Demo class with default (not specified at all) access. It raises compilation error. The subclass can have either same or stronger access like public or same protected. But, it cannot have default or private.

Why the methods of an interface should be overridden with public only?

With the above rule, now you get the answer. The methods of an interface must be public, if not mentioned, takes by default as public. So, the subclass which implements the interface should override with the same specifier or more but not less. No stronger specifier than public exists in Java. For this, reason, all the methods of interface must be overridden with public only.

Rules of exceptions also must be taken care in method overriding.

10 thoughts on “Rules of Access Specifiers in Method Overriding

  1. Nanthakumar

    Hi,

    The question is the logic behind the below rule?

    The subclass overridden method cannot have weaker access than super class method.

    the above answers describe the rules with example.but my question is why?

  2. khushbu

    Hello,
    I have same question as Praveen Basavaraj have.whats the reason behind this statement.
    The subclass overridden method cannot have weaker access than super class method..

    1. S. Nageswara Rao, Corporate Trainer Post author

      That is,

      if in super class there is a method like

      protected void calculate() { }

      it must be overridden in subclass as either

      protected void calculate() { }

      or

      public void calculate() { }

      but cannot be

      void calculate() { } // with default

      or

      private void calculate() { }

  3. Praveen Basavaraj

    Hi Nageswara Rao,

    This website is too good for beginners as well as exp. developers.
    I need a clarification on-
    “The subclass overridden method cannot have weaker access than super class method”
    We can remember this rule, but what is the inner view? In case subclass is allowed to have weaker access, how does that impact?
    Could you explain with an example?

    Thanks a lot
    Praveen

  4. Rajesh

    every one till now was telling that in method overriding the specifier must be same.
    I understood it first time by this site that the weaker will not work….
    I did the practical of this and you are absolutely right sir

    thanks alot

Leave a Reply

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