Results 1 to 3 of 3
- 01-23-2013, 09:04 PM #1
Member
- Join Date
- Nov 2010
- Posts
- 24
- Rep Power
- 0
Overridable method call in the constructor - question
I have a simple Java class with couple of private attributes in it.
In the constructor of the class I'm setting the values of the attributes like this:
My question relates to using the setter method in the constructor for setting the attribute value.Java Code:private string attr1; public ClassName(String value) { this.attr1 = value; }
If the method is public I get the message from the title of this topic.
When I change it to private everything is ok but do I need it then, since the private methods can be used from inside the class, or should I use the first example?
To reformulate my question, should I use the class private setter method to set the class private attribute in the constructor or not?
Does the performance suffer if I use it?
To help You even more in answering, I will not have the need to set the attribute of the class outside the class.
Thank You.
- 01-23-2013, 10:10 PM #2
Moderator
- Join Date
- Feb 2009
- Location
- New Zealand
- Posts
- 4,547
- Rep Power
- 11
Re: Overridable method call in the constructor - question
The warning message has to do with the fact that "best practice" say you should not call overridable methods in your constructor. The problem is described at javapractices.com - with associated aspects of the problem at the links at the bottom of the page. Basically the object is not fully initialized when the overridden method is called. (I know, you aren't overriding anything, but if the setter is not private, it *might* be overridden by you or someone else...)
- 01-24-2013, 09:58 AM #3
Moderator
- Join Date
- Apr 2009
- Posts
- 10,481
- Rep Power
- 16
Re: Overridable method call in the constructor - question
Make the setter final, unless you expect a subclass to change how the setter functions (unikely).
Indeed, unless you can envisage your class being subclassed, and that will be something that should be apparent from your design, then you may as well make the class 'final' instead.Please do not ask for code as refusal often offends.
Similar Threads
-
call default constructor inside of parameterized constructor after conditional check
By Googol in forum New To JavaReplies: 5Last Post: 08-11-2012, 09:50 AM -
Java - Constructor Method versus Constructor
By brocksoffice in forum New To JavaReplies: 1Last Post: 08-01-2012, 09:17 AM -
Is there anyway not to call superclass constructor ?
By fatabass in forum New To JavaReplies: 4Last Post: 01-29-2012, 09:01 PM -
How to call a master constructor from a minor constructor?
By b.m in forum New To JavaReplies: 5Last Post: 12-14-2011, 01:47 PM -
constructor vs overridable method
By pepe34 in forum New To JavaReplies: 2Last Post: 10-10-2011, 10:26 PM


LinkBack URL
About LinkBacks
Reply With Quote

Bookmarks