0

Probably it's a dumb question, but why in Java I can extend visuability of access modifiers in subclasses? So let's say I have the following code:

package a:

public class Parent
{
    private String name;

    void setName(String name)
    {
        this.name = name;
    }
}

in the same package:

public class Child extends Parent
{
    @Override
    public void setName(String name)
    {
        super.setName(name);
    }
}

And then in package b I'll be able to call

Child c = new Child;
c.setName("some-bad-name");

So I will be able to change the field value through the method, which is initially supposed to be called only from the classes of the same package and not be changed through some code in other packages.

So in case in Java we would be able not extend, but only use the same visibility as in superclass - I won't be able to change 'name' field like that. I know about Liskov Substitution Princip and it explains why in subclass I should use access modifier with visuability not less then in superclass, but I'm struggling to understand why I could extend it.

Binary Code
  • 33
  • 1
  • 7
  • 1
    You might ask the same question about why you can add new methods in subclasses - y'know, the parent class isn't meant to have the `foo()` method, but the subclass adds it. Because... you can; and because it's no less visible than the method in the parent class, the subclass is Liskov-subtitutable. – Andy Turner Apr 18 '17 at 20:03
  • But if you want to use the Child class you have to import it first! So both Parent and Child stay in packageA. But using the import you access them from a class in packageB. This is absolutely correct. Why are you struggeling with this? –  Apr 18 '17 at 20:09

0 Answers0