Results 1 to 4 of 4
Thread: Compostion
- 08-17-2011, 08:28 PM #1
Member
- Join Date
- Jul 2011
- Posts
- 10
- Rep Power
- 0
Compostion
Hi Every one . I created two class Human and Employee and then create one object from human in side employee , but when run my program compiler return error
Exception in thread "main" java.lang.NullPointerException
at Employee.main(Employee.java:15)
Java Code:public class Human{ private String name; public void setName(String n){ name = n; } public String getName(){ return name; } } public class Employee{ private String id; public Human h; private void setEmployee(String id){ this.id = id; } private String getEmployee() { return id; } public static void main(String[] args){ Employee emp = new Employee(); emp.h.setName("ehsan"); } }
Last edited by pbrockway2; 08-17-2011 at 11:14 PM. Reason: code tags added
- 08-17-2011, 11:15 PM #2
you never initialized your human. You declared it with "public Human h;" But you have to initialize it before you can make reference to it, and the constructor is a good place to do that.
Java Code:public class Employee{ private String id; public Human h; public Employee(){ h = new Human(); } private void setEmployee(String id){ this.id = id; } private String getEmployee() { return id; } public static void main(String[] args){ Employee emp = new Employee(); emp.h.setName("eshan"); } }
Last edited by sehudson; 08-17-2011 at 11:17 PM.
- 08-17-2011, 11:22 PM #3
Moderator
- Join Date
- Feb 2009
- Location
- New Zealand
- Posts
- 4,716
- Rep Power
- 17
Please use code tags: put [code] at the start of the code and [/code] at the end. That way the code will be readable when it appears here.
Exception in thread "main" java.lang.NullPointerException
at Employee.main(Employee.java:15)
Java Code:foo[i]; // exception when foo is null bar.baz(); // exception when bar is null
Java Code:emp.h.setName("eshan");
- 08-18-2011, 09:31 AM #4
Member
- Join Date
- Jul 2011
- Posts
- 10
- Rep Power
- 0
Similar Threads
-
Compostion
By ehsan in forum New To JavaReplies: 1Last Post: 08-16-2011, 07:17 PM
Bookmarks