简体   繁体   English

在超类对象的向量中访问子类方法

[英]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 instanceof in order to differentiate which subclass each object is a part of. 我将使用instanceof来区分每个对象属于哪个子类。

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? 访问向量中每个对象的子类方法的最有效方法是什么?

You need to cast the object to the subclass inside of an instanceof guard. 您需要将该对象强制转换为instanceof Guard内部的子类。

if (obj instanceof MySubclass)
    ((MySubclass)obj).mySubclassMethod();

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 {
    @Override
    public void mySublcassMethod() { ... }
    ...
}
...

MySuperclass obj = [actually a Subclass];
obj.mySubclassMethod(); // uses the implementation from MySubclass

I think what you want to do is to create the method as abstract in your superclass. 我认为您想要做的是在您的超类中将方法创建为抽象方法。 Then, what you will do is override this method in each of your subclasses. 然后,您要做的是在每个子类中重写此方法。 This will allow you to access that method for all the different objects in that vector of yours. 这将允许您访问该向量中所有不同对象的方法。

I'm assuming this method will vary depending on your subclass, otherwise, why wouldn't you just write that method in the superclass in the first place. 我假设该方法将根据您的子类而有所不同,否则,为什么您不首先在超类中编写该方法。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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