highQualityBean
highQualityBean

Reputation: 59

Using an overridden method from an abstract class (Java)

I have three classes, a SuperClass, a SubClass, and a testing class. The SuperClass is abstract, and the SubClass extends the SuperClass, the testing class has no relationship to either of them. So

public abstract class SuperClass {...}
public class SubClass extends SuperClass {...}
public class TesterClass {...}

Both the SuperClass and the SubClass have a toString() method, so it looks more like

public abstract class SuperClass {
    public String toString(){...};
    ...
}
public class SubClass extends SuperClass {
    public String toString(){...};
    ...
}
public class TesterClass {...}

What I need to do is use the SuperClass's toString() method within the tester class. I've tried casting and object from the SubClass to the SuperClass and using the method from there, but it ends up using the toString() method from the SubClass. (And after I tried using a little bit of reflection to see what class Java thought the object was it looks like it thought it was still the SubClass even after casting). I've thought about trying to use reflection to directly get the method I want from the SuperClass then calling on the object using invoke(), but that seems like a really messy solution.

Any help at all would be a big help, even if it's just pointing me to a concept I haven't heard of yet. Thank you!

Upvotes: 3

Views: 1320

Answers (1)

dreamcrash
dreamcrash

Reputation: 51423

Within the class TesterClass you can create a class that extends the abstract SuperClass, then you test toString of that subclass. Since, you did not override the toString of that subclass, when you call its toString you will be actually testing the toString from the super class, (i.e., SuperClass)

Alternatively, you can in your test method 1) create an inner anonymous class of type SuperClass; 2) implement its abstract methods (i.e., just ignoring them because they will not be tested). 3) test the toString of the inner anonymous class:

public class TesterClass {

     void test_super_class_to_String(){
          SuperClass myApp = new SuperClass() {
                @Override
                void do_something() {}
            };
       String str = myApp.toString();
       // assert str == ....
    }
}

for a SuperClass that looks like the following

public abstract class SuperClass {
    abstract void do_something();

    public String toString(){  return ...;}
}

Upvotes: 2

Related Questions