+ 1

Polimorphism between different access modifiers

Why does the sub-class access modifier can't be more restrictive than the superclass ? Isn't that should be the opposite ?

1st Jan 2020, 8:51 PM
Elior Badash
Elior Badash - avatar
3 Answers
+ 1
Just an example- Consider there is some message on the server and the same message is on your node(PC) without any internet connection. Isn't the server one easily accessible by others when compared to the one which is on your system? So never give more restrictive access modifier to the method of a sub class which is overriding the same method of the base class.
2nd Jan 2020, 4:04 AM
Avinesh
Avinesh - avatar
+ 3
Because you want to be able to use child class object like parent class object. If class A has public method foo(), then if class B is a child it's foo() method must also be public, otherwise you get this situation: A object = new B();//this is valid object.foo();//not valid because B.foo() is not public Allowing that would mean you have no guarantee any of it's methods are valid. This is one of the reasons why composition is preferred over inheritance. There are several old classes in standard library that shouldn't have been subclasses for reasons like these, throwing surprise exceptions when you're not careful.
1st Jan 2020, 9:57 PM
BlazingMagpie
BlazingMagpie - avatar
+ 2
No. That's not the case.. Super class not expect anything back from the sub class.. But sub class acquires properties from the Base class.. So on giving (super class) , you may have restrictions, but not on taking....
1st Jan 2020, 9:47 PM
Jayakrishna 🇼🇳