Win a copy of Design for the Mind this week in the Design forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

can i have simple example or scenario where this is effective

 
kumar reddi
Greenhorn
Posts: 8
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Methods called from constructors should generally be declared final. If a constructor calls a non-final method, a subclass may redefine that method with surprising or undesirable results.
 
Jeanne Boyarsky
author & internet detective
Marshal
Posts: 34178
340
Eclipse IDE Java VI Editor
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Consider the following code:


The author of Class1 expects type to be set based on the String parameter value. There could be other methods in Class1 that depend on type being set. The author of Class1 assumes it was initialized because he/she set it in the constructor. If it is not set, other methods could throw errors or act unpredictably.

Now the Subclass author decides they would like to extend Class1. They create their own setType() method that does something completely different. Now Class1 doesn't do what it is supposed to anymore causing Subclass to break. Worse the Subclass author wasn't planning to override setType() and isn't aware of it.

The two solutions are to make the method private or final. Private allows Subclass to have its own setType() method. Final gives a compiler error so the Subclass author can name the method something else.
 
Jim Yingst
Wanderer
Sheriff
Posts: 18671
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
[Jeanne]: The two solutions are to make the method private or final.

Making the method static also works.
 
Jeanne Boyarsky
author & internet detective
Marshal
Posts: 34178
340
Eclipse IDE Java VI Editor
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Originally posted by Jim Yingst:
[Jeanne]: The two solutions are to make the method private or final.

Making the method static also works.

In general yes. In my example, setType() access an instance field. So it can't be static.
 
kumar reddi
Greenhorn
Posts: 8
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
thank you very much for your clear explanation.
thanks.
 
rakesh sugirtharaj
Ranch Hand
Posts: 151
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Now Class1 doesn't do what it is supposed to anymore causing Subclass to break.

hey.. i m new to java.. i didnt understand this.. What doesnt class1 do that its supposed to?
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic