AkshaiShah
AkshaiShah

Reputation: 5939

getClassHierarchy() method

I have a superclass Person, which contains the following method:

public String getClasHierarchy()
{
  return "Person";
} //getClassHierarchy

I cannot change this class.

I also have 10 subclasses of person, which i need to add a similar method to in order to return a string consisting of the name of the class, followed by a ">" then followed by the string returned by getClassHierarchy() from the superclass. I can't rely on knowing what the class hierarchy above them is. Somehow, i need to invoke the method from the superclass. Anyone have any ideas?

Thanks a lot

Upvotes: 0

Views: 122

Answers (2)

kosa
kosa

Reputation: 66657

This is one way, there are lot other ways too.

public class TestClass extends TestClassSuper {

    public String getClasHierarchy() {
        System.out.println(super.getClasHierarchy());
        return "Person";
    } //getClassHierarchy

    public static void main(String args[]) {
        try {
            TestClass tc = new TestClass();
        System.out.println(tc.getClasHierarchy());
        } catch (Exception e) {
        }

    }
}


public class TestClassSuper {

    public String getClasHierarchy() {

        return "Super Person";

    } //getClassHierarchy
}

Upvotes: 0

SJuan76
SJuan76

Reputation: 24895

You are looking for the 'super' keyword

return super.getClassHierarchy() + ">MyClassName"

Anyway, this is best done by reflection rather than reinventing the wheel.

Upvotes: 1

Related Questions