Click here to Skip to main content
14,393,196 members
Rate this:
Please Sign up or sign in to vote.
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:

System.out.println("pname:"+e1.getPerson().getAge());
it's throwing NullPointException
Posted
Updated 1-Jul-19 7:35am
v3
Rate this:
Please Sign up or sign in to vote.

Solution 1

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 
   
v4
Comments
Member 13954890 1-Jul-19 10:48am
   
Thank you so much @wseng
wseng 1-Jul-19 11:16am
   
you're welcome
Rate this:
Please Sign up or sign in to vote.

Solution 2

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.
   
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, 503-250 Ferrand Drive Toronto Ontario, M3C 3G8 Canada +1 416-849-8900 x 100