简体   繁体   中英

Returning data from a sub-class

I have a subclass "shopStaff" within class "staff". I have a meathod getPerson which I need to send the data set in staff and the data set in shopStaff as a single string.

This is my code

// in staff

public String getPerson()
{
    return format(name) + format(yearJoined);
}

// in shopStaff

public String getPerson()
{
    super.getPerson();
    return format(department);
}

however, when I invoke the getPerson meathod in the subclass it only returns the department information, not the name and yearjoined (that I only set in the superclass.

I thought when I used the super. meathod it would return everything from the class above in the hierarchy. Is this not the case? If not could anyone tell me how I access the information set in the superclass?

Thanks

CJ

Your return value from super.getPerson() is not returned with the return statement in your current getPerson() method. It is just lost in your code.

You need to change your shopStaff method to return the super class values with your subclass return statement: -

public String getPerson()
{
    return super.getPerson() + format(department);
}

When you call:

super.getPerson();

The return is discarded as it is not stored anywhere. You'd want to do this:

//in shopStaff
public String getPerson() {
  return super.getPerson() + format(department);
}
public String getPerson()
{
    String fromSuper=super.getPerson();
    return fromSuper + format(department);
}

Just calling super will not get data unless you read and use it in subclass.

May be something like this will work:

public String getPerson()
{
    String person = super.getPerson();
    return person+format(department);
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM