Reputation: 1
I'm doing a homework for class right now and it requires me to use private variables from a superclass in one of its subclasses, but I don't know how to. I found a lot of info on changing the superclass which would work, but the assignment says that I'm not allowed to edit the superclass, just its subclasses. Is this even possible?
For context, the assignment is on weekly earnings of different employees and printing out their info(first and last name, employee id, position, and earnings). The first name, last name, and employee id are private and I need to override a method in the superclass in the subclass.
Code from superclass:
public String toString(){
return "Name: " + firstName + " " + lastName + ", ID: " + employeeId;
}
Code from subclass(that I'm writing)
// Override public String toString() here
/*public String toString(){
return ("Name: " + firstName + " " + lastName + ", ID: " + employeeId + " Position: Boss");
}*/
I tried using get and set within the subclass, but that obviously doesn't work.
Upvotes: 0
Views: 77
Reputation: 1751
If you just need to toString()
output, you could use super.toString()
.
public String toString() {
return super.toString() + " earnings: " +earnings;
}
Upvotes: 1
Reputation: 846
Reflection API is here to help. In your inheriting class, use:
Field field = super
.getClass()
.getDeclaredField("firstName");
field.setAccessible(true);
String firstname = (String) field.get(super);
Upvotes: 0