NeverendingFlame42
NeverendingFlame42

Reputation: 1

How to access private variable from Superclass in Subclass without changing Superclass? (Java)

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

Answers (2)

bvanvelsen - ACA Group
bvanvelsen - ACA Group

Reputation: 1751

If you just need to toString() output, you could use super.toString().

    public String toString() {
        return super.toString() + " earnings: " +earnings;
    }

Upvotes: 1

Christoph Dahlen
Christoph Dahlen

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

Related Questions