When overriding a method, why can I increase access but not decrease it?

Viewed 52571

Why does Java specify that the access specifier for an overriding method can allow more, but not less, access than the overridden method? For example, a protected instance method in the superclass can be made public, but not private, in the subclass.

8 Answers

Take an example given below

 class Person{
 public void display(){
      //some operation
    }
 }

class Employee extends Person{
   private void display(){
       //some operation
   }
 }

Typical overriding happens in the following case

Person p=new Employee();

Here p is the object reference with type Person(super class) when we are calling p.display(). As the access modifier is more restrictive, the object reference p cannot access child object of type Employee

To re-word what's already been said, it has to do with how Java is compiled into bytecode which is then interpreted by the JVM. when a child class overrides one of its parents methods, the compiler uses the reference type to determine which of the two methods to use. Then the JVM uses the object type during runtime to determine which method should truly be used.

In the example above; Animal lion = new Lion(), when lion.getName() is called, the compiler uses the Animal version of the method and the JVM replaces it/can replace it with the Lion version because it "fits" perfectly. But if Lion were allowed to restrict getName() more than Animal restricted getName(), you could get around the restriction because the compiler would treat it like its unrestricted if a Lion object has an Animal reference.

To solve this, java makes it illegal for the child to make an overridden method more restricted than the method its overriding.

Related