Results 1 to 3 of 3
  1. #1
    kudwn is offline Member
    Join Date
    Oct 2010
    Posts
    4
    Rep Power
    0

    Default 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:

    Java Code:
    public Item(Container c) {
        c.add(this);
    }
    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?

    Thanks!
    Last edited by kudwn; 10-11-2010 at 09:40 AM. Reason: formatting

  2. #2
    Ronin is offline Senior Member
    Join Date
    Oct 2010
    Posts
    393
    Rep Power
    5

    Default

    Crosspost


    Regards.

  3. #3
    Fubarable's Avatar
    Fubarable is offline Moderator
    Join Date
    Jun 2008
    Posts
    19,315
    Blog Entries
    1
    Rep Power
    26

Similar Threads

  1. this keyword
    By coltragon in forum New To Java
    Replies: 10
    Last Post: 03-01-2010, 10:20 AM
  2. How to use Switch keyword
    By Java Tip in forum java.lang
    Replies: 0
    Last Post: 04-23-2008, 09:07 PM
  3. Replies: 0
    Last Post: 12-19-2007, 10:10 AM
  4. Replies: 0
    Last Post: 12-19-2007, 10:01 AM
  5. Use of this keyword
    By Java Tip in forum Java Tip
    Replies: 0
    Last Post: 11-18-2007, 08:32 PM

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •