Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why java doesn't allow to make an instance method of parent class as more restrictive in child class

Polymorphism allows the programmer either to inherit, override or to overload an instance method of Parent Class.

But, it won't allow to make an instance method of parent class as more restrictive in child class. i.e it wont allow to use same name of parent class instance method, to declare as private in the child class.

Also JVM identifies the parent class version of an instance method, if child class didn't override it.

Similarly why don't JVM identifies the parent class version of an instance method, if the child class makes it more restrictive?

The more restrictive method of parent class in child class can be considered as child class specific method instead of overridden method by compiler.

like image 529
acvbruno Avatar asked Nov 23 '25 09:11

acvbruno


1 Answers

This is all done in order to follow the Liskov Substitution Principle.

In order for inheritance in object oriented programming to behave as expected, a child class should be able to be substituted out for a parent class instance and not break a user of the class.

Making a child method more restrictive is basically saying "I don't want this method to be visible". Having the JVM automatically substitute out the parent class implementation in this case would just add a huge amount of confusion - just changing the call behavior might cause very unexpected behavior, even completely within the child class...

like image 123
Reed Copsey Avatar answered Nov 24 '25 23:11

Reed Copsey



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!