简体   繁体   中英

Private vs final regarding polymorphism in Java

What exactly is the purpose of having private access modifier for the methods in Java if they are prohibited for the modification by the final modifier as well?

And The Java Language Specification explicitly notes that:

A method can be declared final to prevent subclasses from overriding or hiding it.

Then why not to simply mark a method as final?

The private modifier and final keyword are different things and have different purposes.

Private is an access modifier. Only code in the same class can call private methods or access private fields. Final is a keyword used to define an entity that can only be assigned once.

A final field can not have its value changed, ever. But it can be read by any other class. So, if you do not want it to be read by other classes, then you can set it as private field.

A private field can have its value change, but not by other classes, only by the class it belongs. If you do not want it to be changed, ever, then you can set it as a final field.

The same goes to methods. A private method is not visible to others classes, that's why it can't be overridden. The main goal here is to prevent access by others classes.

A final method can't be overridden, but it is visible to other classes.

I think that's the main difference.

The difference is in how code maintenance is impacted.

Private methods are invisible to the subclasses, they are not part of the interface exposed. That means the superclass can change those methods freely without worrying about impacting code that subclasses it. At some point the private methods are called by more public ones that affect the subclasses, but you have more scope to move code around.

If you make the method final but not private, then subclasses can call it directly, and you have to make sure any changes you need to make to them don't cause breakage in the subclasses.

If your class is part of a project used by others, you can't know who is using what methods of your superclass, so you can get into a situation where you can't safely change the behavior of anything once it's exposed. Better to keep as much private as possible.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM