Results 1 to 6 of 6
- 11-02-2009, 03:35 PM #1
Member
- Join Date
- Nov 2009
- Posts
- 4
- Rep Power
- 0
Recursive Class throws NullPointerException
Hi all,
I literally just started with Java and I am experimenting with OOP, but this puzzles me:
I have something that resembles the following (plus getters, setters etc):
Java Code:public class person { public String name; public person father; public ArrayList<person> children; }
Now I wanted to create relationships:
However, here is where I get the NullPointerExceptions.Java Code:person p1 = new person(); p1.setName("Lucy"); person p2 = new person(); p2.setName("Fred"); [B]p1.father= p2; p2.children.add(p1);[/B]
It doesn't seem to work this way, and I just assume I am not yet in the right mind set for OOP to understand what's wrong here.
btw, using a setter for the first bold line:
doesn't work either. same exception.Java Code:p1.setFather(p2);
Can anyone enlighten me, please?Last edited by freeBatjko; 11-02-2009 at 03:40 PM. Reason: added setter alternative
- 11-02-2009, 03:44 PM #2
Could u paste the complete code with code tag?
Ramya:cool:
- 11-02-2009, 06:59 PM #3
Senior Member
- Join Date
- Aug 2009
- Posts
- 2,388
- Rep Power
- 6
does not create a list of person. It only creates a reference that is automatically initialized to null. Trying to add anything to it will throw the N.P.EJava Code:public ArrayList<person> children;
You need to doto initialize the list of children before you try to manipulate it.Java Code:ArrayList<person> children = new ArrayList<person>();
- 11-02-2009, 08:56 PM #4
Member
- Join Date
- Nov 2009
- Posts
- 4
- Rep Power
- 0
- 11-03-2009, 02:48 AM #5
can i use this as a field in my class though?
Yes, you can declare the variable and later initialize it in a constructor:
or you can declare and initialize it in one step:Java Code:public class Person { public String name; public person father; public ArrayList<Person> children; public Person() { children = new ArrayList<Person>(); } }
Java Code:public class Person { public String name; public person father; public ArrayList<Person> children = new ArrayList<Person>();
- 11-03-2009, 09:18 AM #6
Member
- Join Date
- Nov 2009
- Posts
- 4
- Rep Power
- 0
Similar Threads
-
Execute() throws an NPE
By mjz in forum JDBCReplies: 0Last Post: 08-06-2009, 02:25 AM -
NullPointerException even when class is instantiated as expected
By DCC1 in forum New To JavaReplies: 17Last Post: 07-12-2009, 06:42 PM -
another NullPointerException in LinkedList class
By muffstuff in forum New To JavaReplies: 7Last Post: 04-10-2009, 10:51 PM -
throws
By jdgallag in forum New To JavaReplies: 14Last Post: 02-11-2009, 01:07 AM -
throws Exception
By javaplus in forum New To JavaReplies: 1Last Post: 11-06-2007, 07:32 PM


LinkBack URL
About LinkBacks
Reply With Quote

Bookmarks