Click here to Skip to main content
15,445,560 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
I have a Person class (saved as Person.java) . The code is given below.
public class Person {

    private int age1;

    public int getAge() {
        return age1;
    }

    public void setAge(int age1) {
        this.age1 = age1;
    }
}

Then i have a Employee class which takes Person as data type. Code is given below.(saved as Employee.java)
public class Employee {

    Person person;
    private String employeeName;

    public Person getPerson() {
        return person;
    }

    public void setPerson(Person person) {
        this.person = person;
    }

    public String getEmployeeName() {
        return employeeName;
    }

    public void setEmployeeName(String employeeName) {
        this.employeeName = employeeName;
    }
}

Then I have main method in a separate class Main (Main.java). Code is given below.
public class MainEmployee {

    public static Employee getEmployeeDetails() {
        Scanner s = new Scanner(System.in);
        Employee e = new Employee();
        Person p = new Person();
        System.out.println("Enter name:");
        e.setEmployeeName(s.nextLine());
        System.out.println("Enter age1:");
        p.setAge(s.nextInt());
        return e;
    }

    public static void main(String args[]) {
        Employee e1 = getEmployeeDetails();
        System.out.println("name:" + e1.getEmployeeName());
        System.out.println("pname:" + e1.getPerson().getAge());//here it's showing error
    }
}


What I have tried:

Java
System.out.println("pname:"+e1.getPerson().getAge());
it's throwing NullPointException
Posted
Updated 1-Jul-19 6:35am
v3

You are not setting p to e,thats why you will get null pointer exception. Write like this
System.out.println("Enter name:");
e.setEmployeeName(s.nextLine());
System.out.println("Enter age1:");
p.setAge(s.nextInt()); // set person's age to person
e.setPerson(p);  // set person to employee 
 
Share this answer
 
v4
Comments
Member 13954890 1-Jul-19 10:48am    
Thank you so much @wseng
wseng 1-Jul-19 11:16am    
you're welcome
Storing the age in the class is not a good idea, since it is only correct at the time it is entered. You should store the date of birth as a Date or DateTime object, and calculate the age when you need to display it.
 
Share this answer
 
Comments
Member 13954890 2-Jul-19 1:24am    
ok thank you

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900