0

Example:

class Parent {
    public void func(){
        System.err.println("parnet");
    }
}

class Child extends Parent {
    @Override
    protected void func(){
        System.err.println("child");
    }
}

is illegal but if we switch the visibility it is legal. What's the reason why it is designed this way? I can't make much sense out of it.

halfer
  • 19,824
  • 17
  • 99
  • 186
user1861088
  • 1,683
  • 2
  • 15
  • 17

2 Answers2

1

It's because someone could be using a 'Parent' object to refer to an instance of the 'Child' object, and reducing the visibility would break the inheritance 'contract'.

Imagine if you had a class 'Cat' that extends 'Animal' which had public methods to breathe() and eat().

Now if your 'Cat' class made breathe() private, then someone that has an Animal referring to your cat couldn't call breathe() on the cat (and we can't have unhappy cats in Java!)

halfer
  • 19,824
  • 17
  • 99
  • 186
vikingsteve
  • 38,481
  • 23
  • 112
  • 156
0

If you get an instance to the parent class , you should be able to reach all of its public methods . That's part of the contract.

The Child class has the "is a" property compared to the parent , therefore it can do at least what the Parent can do.

For example:

List<Parent> parents=new List<Parent>();
parents.add(new Child());
...
parents.get(0).func(); // you should always be able to call it , since it's a Parent instance . 
android developer
  • 114,585
  • 152
  • 739
  • 1,270