Results 1 to 6 of 6
- 10-11-2010, 08:38 AM #1
Member
- Join Date
- Oct 2010
- Posts
- 4
- Rep Power
- 0
Using 'this' keyword in constructor
So I've ran into a small problem here that I can't seem to get around. I'm writing a class Item and when the constructor is invoked, I need the Item to be added to an instance of another class Container. Here is the code for the constructor:
The problem is that I get a null pointer exception when calling the method add in for the Container. I think the problem lies in my using the 'this' keyword in the constructor, before the object has been fully constructed. Any ideas for getting around this?Java Code:public Item(Container c) { c.add(this); }
Thanks!
- 10-11-2010, 08:50 AM #2
- Join Date
- Sep 2008
- Location
- Voorschoten, the Netherlands
- Posts
- 11,400
- Blog Entries
- 7
- Rep Power
- 17
As the first line of your constructor print out 'c':
I suspect that c is null; your 'this' reference is fine in a constructor.Java Code:System.out.println(c);
kind regards,
Jos
- 10-11-2010, 09:04 AM #3
Member
- Join Date
- Oct 2010
- Posts
- 4
- Rep Power
- 0
Actually my constructor is slightly more complex than this. I just simplified it a bit for ease of reading. It contains a line to ensure c is not null:
Have any other ideas?Java Code:public Item(String description, Container c) { if (c != null && c.find(description) == null) { this.container = c; this.description = description; container.add(this); } }
Thanks!
- 10-11-2010, 09:08 AM #4
- Join Date
- Sep 2008
- Location
- Voorschoten, the Netherlands
- Posts
- 11,400
- Blog Entries
- 7
- Rep Power
- 17
- 10-11-2010, 09:26 AM #5
Member
- Join Date
- Oct 2010
- Posts
- 4
- Rep Power
- 0
The null pointer exception occurs at line 22, which is the following:
My original thought was that 'this' is being used as a parameter for a method of an external class before it has even been fully constructed. Would you know of a way to fully construct the Item first, and then add it to the Container?Java Code:container.add(this);
I really appreciate your help.
- 10-11-2010, 09:47 AM #6
- Join Date
- Sep 2008
- Location
- Voorschoten, the Netherlands
- Posts
- 11,400
- Blog Entries
- 7
- Rep Power
- 17
Similar Threads
-
Using 'this' keyword in constructor
By kudwn in forum New To JavaReplies: 2Last Post: 10-11-2010, 12:12 PM -
this keyword
By coltragon in forum New To JavaReplies: 10Last Post: 03-01-2010, 09:20 AM -
Calling constructor of parent class from a constructor
By Java Tip in forum Java TipReplies: 0Last Post: 12-19-2007, 09:10 AM -
Calling constructor of same class from a constructor
By Java Tip in forum Java TipReplies: 0Last Post: 12-19-2007, 09:01 AM -
Use of this keyword
By Java Tip in forum Java TipReplies: 0Last Post: 11-18-2007, 07:32 PM


LinkBack URL
About LinkBacks
Reply With Quote

Bookmarks