Java对象继承问题列表

use*_*976 0 java

我有一个名为Interpreter的课程.它由几个类继承,包括一个名为LoadStep的类.

我创建了一个对象列表:

public static List<Interpreter> fileActions = new ArrayList<Interpreter>();
Run Code Online (Sandbox Code Playgroud)

以这种方式添加对象:

if (actionName.equals("LOAD")) {
    LoadStep loadAction = new LoadStep();
    fileActions.add(loadAction);
}
Run Code Online (Sandbox Code Playgroud)

当试图访问我的对象并调用他们的方法时,我无法访问子类方法.我期待,因为当我尝试使用getClass()来查看对象类时,我得到了子类名.

    for (int i = lineNumber; i < Test.fileActions.size(); i++) {

        System.out.println(Test.fileActions.get(i).getClass());
        if (Test.fileActions.get(i) instanceof LoadStep) {
            LoadStep newAction = Test.fileActions.get(i);
            myMemoryAddress = Test.fileActions.get(i).getMemoryAddress(); //This line gives me Cannot Find Symbol, as getMemoryAddress is LoadStep's method, and not Interpreter
        } 
    }
Run Code Online (Sandbox Code Playgroud)

print语句给了我:

class test.LoadStep
Run Code Online (Sandbox Code Playgroud)

Con*_*Del 5

你需要对你的LoadStep实例进行类型转换,比如

Interpreter step = ...;
if (step instanceof LoadStep) {
  LoadStep sub = (LoadStep) step;
  sub.invokeSubclassMethod(...)
}
Run Code Online (Sandbox Code Playgroud)