eoi*_*nzy 3 java polymorphism subclass superclass
我会发布一些代码然后问我的问题,因为我认为它需要一些解释.所以这是我的超类的基本表示:
public abstract class ModeOfTransport {
public abstract void updateView(String name);
}
Run Code Online (Sandbox Code Playgroud)
以下是我的子类的一些示例:
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");
}
}
Run Code Online (Sandbox Code Playgroud)
我有一个switch
意图是能够决定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);
}
Run Code Online (Sandbox Code Playgroud)
我的目标是打印出TRAIN
或者BUS
.目前,它什么都没打印!我猜是因为它在父类中调用抽象方法,它没有主体.
谁能为我解释这个问题?
此外,作为一个附带问题,这是否属于polymorphism
或inheritance
?
谢谢!
我已经成功了.我不知道你做错了什么,但也许你会从这个源代码中弄明白.
package transport;
/**
* ModeOfTransport description here
* @author Michael
* @link http://stackoverflow.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 http://stackoverflow.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 http://stackoverflow.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);
}
}
Run Code Online (Sandbox Code Playgroud)