Queue Queue - 1 year ago 80
Java Question

Accessing subclass methods within a vector of of superclass objects

I am using a vector to store objects of an abstract superclass. I need to access a method(s) within the derived subclasses of each object in the vector. I will be using

in order to differentiate which subclass each object is a part of.

I do not have permission to write to the abstract class.

Currently the compile error I am getting is:

Error: cannot find symbol
symbol: method <mySubclassMethod>()
location: class <MyAbstractClass>

What is the most effective way of going about accessing the subclass methods of each object within my vector?

Answer Source

You need to cast the object to the subclass inside of an instanceof guard.

if (obj instanceof MySubclass)

More broadly, if the method should be available in all of your subclasses, you should add it to the abstract superclass. Then, when you call the method on the 'uncasted' abstract superclass object, it will use the implementation from the proper subclass.

public abstract class MySuperclass {
    public abstract void mySubclassMethod();

public class MySubclass extends MySuperclass {
    public void mySublcassMethod() { ... }

MySuperclass obj = [actually a Subclass];
obj.mySubclassMethod(); // uses the implementation from MySubclass
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download