有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

java如果只初始化了超类对象,是否可以调用特定于子类的方法?

让我们从一个非常简单的例子中推断: a类:

public class a{
public a{}

子类b继承了a:

public class b inherits a{
public b{super}
public void customMethodB(){}

子类c继承了一个:

public class c inherits a{
public c{super}
public void customMethodC(){}

主要内容:

public class Main{
public static void main(String[] args){
a newObject = null;
//User can now choose through input if he wants to create b or c. Lets say he creates b:
newObject = new b();
//His choice is stored in a string.
String userChoice = b;
//I now call the general object from another method for the user to interact with.
//(I have a feeling it is here my problem is).
}

userInteraction(a newObject, String userChoice){
if (userChoice.equals("b"){
newObject.customMethodB();
}
else if (userChoice.equals("c"){
newObject.customMethodC();
}

}

这里是我的问题:我不能调用customMethodB或customMethodC,即使该对象在main中被创建为b。这是因为userInteraction方法中的参数类型为a吗?在不创建方法来传递特定子类类型的情况下,是否可以执行类似的操作


共 (1) 个答案

  1. # 1 楼答案

    类型a中不存在方法customMethodB。 为了调用此方法,必须强制转换对象(这里可以向下强制转换)

    if (userChoice.equals("b") && newObject instanceof b){
    ((b)newObject).customMethodB();
    }