Hi,
I'm writing some Java code. In some of my setter methods, I do some error / value checking. So I decided to use these setter methods from within my constructor. But in Netbeans, I get a warning that it "might not be safe" to do so. I found this source trying to explain it like this:
However, this doesn't quite sense to me. If I extend a class and then override some setter methods, I actually want that overridden setter method to be called, not my original one.
If this really isn't the way to do things, how else can I use the logic I have in my setter methods from within my constructor? Currently, I'm using a workaround of using a private (thus impossible to override) setter method which gets called by the public setter method and by my constructor. I guess this should solve the extending issues, am I correct?
Thanks!
I'm writing some Java code. In some of my setter methods, I do some error / value checking. So I decided to use these setter methods from within my constructor. But in Netbeans, I get a warning that it "might not be safe" to do so. I found this source trying to explain it like this:
and: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.
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.
However, this doesn't quite sense to me. If I extend a class and then override some setter methods, I actually want that overridden setter method to be called, not my original one.
If this really isn't the way to do things, how else can I use the logic I have in my setter methods from within my constructor? Currently, I'm using a workaround of using a private (thus impossible to override) setter method which gets called by the public setter method and by my constructor. I guess this should solve the extending issues, am I correct?
Thanks!