Change the access modifier of an overridden method in Java?

后端 未结 5 1666
-上瘾入骨i
-上瘾入骨i 2020-12-28 15:32

Is there a reason one can change the access modifier of an overridden method? For instance,

abstract class Foo{
    void start(){...}
}

And

5条回答
  •  梦毁少年i
    2020-12-28 16:23

    The explaination is this:-

    It's a fundamental principle in OOP: the child class is a fully-fledged instance of the >parent class, and must therefore present at least the same interface as the parent class. >Making protected/public things less visible would violate this idea; you could make child >classes unusable as instances of the parent class.

     class Person{
     public void display(){
      //some operation
     }
     }
    
    class Employee extends Person{
    private void display(){
       //some operation
     }
    
    
     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

提交回复
热议问题