Results 1 to 4 of 4
Thread: Compostion
- 08-17-2011, 07: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 10:14 PM. Reason: code tags added
- 08-17-2011, 10: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 10:17 PM.
- 08-17-2011, 10:22 PM #3
Moderator
- Join Date
- Feb 2009
- Location
- New Zealand
- Posts
- 4,547
- Rep Power
- 11
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.
This exception means that you are trying to use something as if it had a value when it is really null. Common cases look likeException in thread "main" java.lang.NullPointerException
at Employee.main(Employee.java:15)
I am guessing line 15 isJava Code:foo[i]; // exception when foo is null bar.baz(); // exception when bar is null
Check, by using System.out.println(), what the values of emp and h are. One of them is null! Once you have found the culprit (or by using sehudson's advice, but its good to check) search for whereever you thought you had assigned it a non null value and see why that didn't happen.Java Code:emp.h.setName("eshan");
- 08-18-2011, 08: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, 06:17 PM


LinkBack URL
About LinkBacks
Reply With Quote
Bookmarks