Creating a class, we design it in such a way that successor classes can work with it through a special interface of public methods. We mark the hidden implementation as private . But how to understand what is better to use - private or final ? And is the use of both meaningful?

  • one
    final modifier prohibits any override. It does not matter that it is a method or a field. You can use it, but not redefine it. private in turn is the definition of the scope of a field or method. As you described below - these are completely different things. If you want to use private protect the method from being overridden, this is not the best option. - Rootware

1 answer 1

You are right in one thing - both final and private - both do not allow you to override the method in the heir.

However, their purpose is completely different. It's like comparing a car and a plane just because they have wheels.

And now an example. What if you want to make an open ( public ) method, but without the possibility of overriding? private will not help you here.

Let there be a Dog class and a Bulldog class (and you don’t want the Dog class to be able to change the number of legs of a dog, because all dogs have 4 legs, right?):

 public class Dog { public final int getLegsCount() { return 4; } } public class Bulldog extends Dog { } 

And in your program you can always get the number of legs of a dog, be it a bulldog or just some abstract dog:

 Dog dog = new Dog(); dog.getLegsCount(); Dog bulldog = new Bulldog(); bulldog.getLegsCount(); Bulldog bulldog2 = new Bulldog(); bulldog2.getLegsCount(); 

Although you can get a number of legs, but you can not make a dog with 3 legs, for example.

On the other hand, if you getLegsCount() method as private rather than public final , you would not be able to call it in your program (outside the Dog class).

  • Vooot. Chic answer. Thank you) - Flippy