'Basic Inheritance in Java
I'm currently learning and working on an exercise for class. I'm able to get a printout that resembles what I need, but the data isn't populating with test inputs. Name comes back null, Age: 0 and ID: 0.
Here's the scenario:
Assign courseStudent's name with Smith, age with 20, and ID with 9999. Use the printAll member method and a separate println statement to output courseStudents's data. Sample output from the given program:
Name: Smith, Age: 20, ID: 9999
// ===== Code from file PersonData.java =====
public class PersonData {
private int ageYears;
private String lastName;
public void setName(String userName) {
lastName = userName;
}
public void setAge(int numYears) {
ageYears = numYears;
}
// Other parts omitted
public void printAll() {
System.out.print("Name: " + lastName);
System.out.print(", Age: " + ageYears);
}
}
// ===== end =====
// ===== Code from file StudentData.java =====
public class StudentData extends PersonData {
private int idNum;
public void setID(int studentId) {
idNum = studentId;
}
public int getID() {
return idNum;
}
}
// ===== end =====
// ===== Code from file StudentDerivationFromPerson.java =====
public class StudentDerivationFromPerson {
public static void main (String [] args) {
StudentData courseStudent = new StudentData();
courseStudent.printAll();
System.out.println(", ID: " + courseStudent.getID());
}
}
// ===== end =====
I'm sure that I'm overlooking something simple, but I'm not sure what. My code is the just the last few lines:
courseStudent.printAll();
System.out.println(", ID: " + courseStudent.getID());
Solution 1:[1]
You need to add set values so you don’t get null and 0 as output. The correct answer is:
courseStudent.setID(9999);
courseStudent.setName(“Smith”);
courseStudent.setAge(20);
courseStudent.printAll();
System.out.print(“, ID: “ + courseStudent.getID());
System.out.println(“”);
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | Mystique |
