Results 1 to 3 of 3
- 06-07-2011, 07:30 AM #1
Member
- Join Date
- Apr 2011
- Posts
- 7
- Rep Power
- 0
overloaded constructors, specifically the use of this(args...)
In overloaded classes, to save space I know I can do this:
is there a way to use the this(...) command not in the first line of the constructor? so instead it would read similar to:Java Code:public class Test{ //fields public Test(args...){ //constructor code } public Test(){ this(someOtherArgs...); } }
thanks!Java Code:... public Test(){ if(...) throw new Exception(...); this(...); }
- 06-07-2011, 07:38 AM #2
No. The call to "this" or "super" MUST be the first line of a constructor. Even if you don't write it, it is still there implicitly.
Since all objects inherit from Object, the above is actuallyJava Code:class Foo { Foo() { // code } }
Java Code:class Foo extends Object { Foo() { super(); //call Object constructor // code } }
- 06-07-2011, 09:00 AM #3
If a constructor throws an exception anywhere in its body, the 'this' object will never be fully instantiated and your program will never get a reference to it. So don't worry about throwing something after calling the superclass constructor; you're not going to get a half-baked object. The only thing you need to worry about is if your constructor (or the super constructor) has side effects like the creation of other objects that aren't local or member variables... like, if your constructor puts something in a Collection that's accessible to other parts of the program, and then throws an exception. You should avoid those kinds of side effects anyway.
Edit: I'm not sure what would happen if a constructor stored a reference to 'this' somewhere outside 'this', and then threw an exception. But again, constructors modifying unrelated objects or references is bad form.Last edited by kjkrum; 06-07-2011 at 09:06 AM.
Get in the habit of using standard Java naming conventions!
Similar Threads
-
JTextArea's KeyListener' overloaded method works only once... what can be a problem?
By nikkka in forum New To JavaReplies: 2Last Post: 05-11-2011, 06:29 PM -
can static methods be overloaded?
By katturv in forum New To JavaReplies: 2Last Post: 10-03-2010, 06:51 PM -
Args[0]
By hakan123 in forum New To JavaReplies: 11Last Post: 12-03-2009, 05:40 PM -
Overloaded method
By Java Tip in forum java.langReplies: 0Last Post: 04-17-2008, 07:42 PM -
Overloaded constructor
By Java Tip in forum java.langReplies: 0Last Post: 04-17-2008, 07:42 PM


LinkBack URL
About LinkBacks
Reply With Quote

Bookmarks