java – 未调用子类抽象方法

我会发布一些代码然后问我的问题,因为我认为它需要一些解释.
所以这是我的超类的基本表示:

public abstract class ModeOfTransport {
    public abstract void updateView(String name);
}

以下是我的子类的一些示例:

public class Bus extends ModeOfTransport {
    @Override
    public void updateView(String stopName) {
        System.out.println("BUS");
    }
}

public class Train extends ModeOfTransport {
    @Override
    public void updateView(String stopName) {
        System.out.println("TRAIN");
    }
}

我有一个开关,旨在能够决定调用哪个版本的updateView():

switch(transportType) {
    case BUS:
        handleInfo(new Bus());
        break;
    case TRAIN:
        handleInfo(new Train());
        break;
    default:
        break;
}

private void handleInfo(ModeOfTransport transportType) {
    transportType.updateView(name);
}

我的目标是打印出TRAIN或BUS.目前,它什么都没打印!我猜是因为它在父类中调用抽象方法,它没有主体.

谁能为我解释这个问题?

另外,作为一个附带问题,这是属于多态还是继承?

谢谢!

解决方法:

我已经成功了.我不知道你做错了什么,但也许你会从这个源代码中弄明白.

package transport;

/**
 * ModeOfTransport description here
 * @author Michael
 * @link https://*.com/questions/14097153/java-subclass-abstract-method-not-being-called/14097167#14097153
 * @since 12/30/12 10:46 PM
 */
public abstract class ModeOfTransport {
    public abstract void updateView(String name);
}

package transport;

/**
 * Bus description here
 * @author Michael
 * @link https://*.com/questions/14097153/java-subclass-abstract-method-not-being-called/14097167#14097153
 * @since 12/30/12 10:47 PM
 */
public class Bus extends ModeOfTransport {
    @Override
    public void updateView(String name) {
        System.out.println("BUS");
    }
}

package transport;

/**
 * Train description here
 * @author Michael
 * @link
 * @since 12/30/12 10:48 PM
 */
public class Train extends ModeOfTransport {
    @Override
    public void updateView(String name) {
        System.out.println("TRAIN");
    }
}


package transport;

/**
 * TransportVisitor description here
 * @author Michael
 * @link https://*.com/questions/14097153/java-subclass-abstract-method-not-being-called/14097167#14097153
 * @since 12/30/12 10:49 PM
 */
public class TransportVisitor {
    public static void main(String[] args) {
        TransportVisitor visitor = new TransportVisitor();
        String [] types = { "TRAIN", "BUS" };
        for (String type : types) {
            visitor.updateView(type);
        }
    }

    public void updateView(String transportTypeName) {
        switch(transportTypeName) {
            case "BUS":
                handleInfo(new Bus());
                break;
            case "TRAIN":
                handleInfo(new Train());
                break;
            default:
                break;
        }
    }

    private void handleInfo(ModeOfTransport transportType) {
        transportType.updateView((String) null);
    }
}
上一篇:java – Polymorphism – 重载/覆盖


下一篇:java – 使用与类关联的条目创建枚举