public class Student extends Person{ private String school; private String studentId;…
- User
public class Student extends Person{ private String school; private String studentId; private int yearStarted;
codepublic void setSchool(String school){ this.school = school; } public String getSchool() { return school; } public void setStudentId(String studentId){ this.studentId = studentId; } public String getStudentId() { return studentId; } public void setYearStarted(int yearStarted){ this.yearStarted = yearStarted; } public int getYearStarted() { return yearStarted; } public void displayDetails(){ Person objPerson1 = new Person(); System.out.println("\nStudent from "+school+" with ID "+studentId+" is "+objPerson1.getFirstName()+" "+objPerson1.getLastName()+" who started on "+yearStarted+"."); }}
It doesn't work, it gives null for FirstName and LastName
Assistant
The issue with your code is that in the
displayDetails()method, you're creating a new instance of thePersonclass, which doesn't have any values set forfirstNameandlastName. To fix this, you should use the current instance of theStudentclass, which inherits thefirstNameandlastNameproperties from thePersonclass. Here's the corrected code:java- User
public class Person { private String firstName; private String lastName;
codepublic void setFirstName(String firstName) { this.firstName = firstName; } public void setLastName(String firstName){ this.lastName = lastName; } public String getFirstName() { return firstName; } public String getLastName() { return lastName; }}
Assistant
The
Personclass you provided is correct, but it's missing a constructor to initialize thefirstNameandlastNameproperties. Here's an updated version of thePersonclass with a constructor:javapublic class Person { private String firstName; private String lastName; public Person(String firstName, String lastName) { this.firstName = firstName; this.lastName = lastName; } public void setFirstName(String firstName) { this.firstName = firstName; } public void setLastName(String lastName) { this.lastName = lastName; } public String getFirstName() { return firstName; } public String getLastName() { return lastName; } }Now, you can create a
Studentobject and set its properties, including the and , like this: