Why should the methods called in the class constructor be final?

I am a Java beginner and I tried to understand the following line from a tutorial on the Oracle website: http://docs.oracle.com/javase/tutorial/java/IandI/final.html

Methods called from constructors should usually be declared final. If the constructor calls a non-final method, a subclass may override this method with unexpected or undesirable results.

I tried to read it several times, trying to understand how a method called from a constructor can be overridden by a subclass. Should I assume that the method called by the constructor is declared inside the constructor class? And why should the final method be declared if it is called inside the constructor? (Unlike inside a nested class or another method?) I could not wrap my head around this statement. An example would be great.

+5
source share
1 answer

This is valid code (compilation):

class Person { Person() { init(); } void init() { // do stuff } } class Employee extends Person { Employee() { super(); } void init() { // do something else } } 

And this is very suspicious. Since Person.init can do something critical to the integrity of the class, there is no guarantee that Employee.init will do it either.

Limiting Person.init to private not enough. Employee.init remains valid, but will be Person.init , which will just be very misleading. It is best to make Person.init final , which prohibit the creation of Employee.init .

+6
source

Source: https://habr.com/ru/post/1209940/


All Articles