Results 1 to 4 of 4
Thread: Setter in constructor
- 11-22-2010, 07:00 AM #1
Member
- Join Date
- Aug 2010
- Location
- Leuven, Belgium
- Posts
- 79
- Rep Power
- 0
Setter in constructor
Hello,
When i write a class in BleuJ with setters in the constructor there is no error or warning.
When i copy this into netbeans, there is a warning.
I have to make the class or the setter final.
What is the reason for that ?
orJava Code:public Name(String name) { this.name = name; }
Java Code:public Name(String name) { setName(name); }
- 11-22-2010, 07:20 AM #2
- Join Date
- Sep 2008
- Location
- Voorschoten, the Netherlands
- Posts
- 11,394
- Blog Entries
- 7
- Rep Power
- 17
If you don't make that class final and don't make the setName( ... ) method private or final someone else is able to extend your class and overrid the setName( ... ) method. Your constructor (in your base class) will call that method in the extending class instead of your implementation. Nobody knows what that method can do; hence the warning ... As a rule of thumb: a constructor shouldn't call methods that can be overriden.
kind regards,
JosWhen people rob a bank they get a penalty; when banks rob people they get a bonus.
- 11-22-2010, 07:49 AM #3
Moderator
- Join Date
- Feb 2009
- Location
- New Zealand
- Posts
- 4,545
- Rep Power
- 11
The method in the extending class will be called before the instance has had a chance to initialise itself. If the extending class's method depends on some initialisation your constructor will defeat that and possibly cause grief.
Java Code:class Base { double value; Base(double value) { this.value = value; report(); } void report() { System.out.println("Value is " + value); } } class Ext extends Base { int div = 1000; Ext(double value) { super(value); } void report() { // this looks innocent enough, but the beahviour // is a little counterintuitive System.out.println("Value in kilounits is " + (value / div)); } } public class Test { public static void main(String args[]) { Ext test = new Ext(12345); } }Last edited by pbrockway2; 11-22-2010 at 07:57 AM.
- 11-22-2010, 03:55 PM #4
Member
- Join Date
- Aug 2010
- Location
- Leuven, Belgium
- Posts
- 79
- Rep Power
- 0
Similar Threads
-
Constructors, Setter & Getter << need some explaining
By A.M.S in forum New To JavaReplies: 4Last Post: 01-01-2009, 12:03 PM -
How to decide whether to use Setter injection or constructor injection in your code
By Java Tip in forum Java TipReplies: 0Last Post: 03-29-2008, 12:38 PM -
How to use Setter Injection and Constructor Injection
By Java Tip in forum Java TipReplies: 0Last Post: 03-29-2008, 12:38 PM -
How to decide whether to use Setter injection or constructor injection in your code
By JavaBean in forum Java TipReplies: 0Last Post: 09-26-2007, 08:29 PM -
How to use Setter injection and constructor injection
By JavaBean in forum Java TipReplies: 0Last Post: 09-26-2007, 08:28 PM


LinkBack URL
About LinkBacks
Reply With Quote

Bookmarks