Chris Headleand
Chris Headleand

Reputation: 6193

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

Upvotes: 0

Views: 79

Answers (4)

Rohit Jain
Rohit Jain

Reputation: 213233

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);
}

Upvotes: 2

Grambot
Grambot

Reputation: 4524

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);
}

Upvotes: 2

Aravind Yarram
Aravind Yarram

Reputation: 80176

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

Upvotes: 1

kosa
kosa

Reputation: 66637

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);
}

Upvotes: 0

Related Questions