class Vehical{}
public class Car extends Vehical {
public static void main(String[] args) {
Vehical v = new Vehical();
Car c = new Car();
boolean is = v instanceof Vehical;
System.out.println("is v instanceof Vehical class - "+is);
is = c instanceof Car;
System.out.println("is c instanceof of Car class - "+is);
is = v instanceof Car;
System.out.println("is v instanceof of Car class - "+is);
is = c instanceof Vehical;
System.out.println("is c instanceof of Vehical class - "+is);
}
}发布于 2020-02-26 22:43:56
Vehicle不是Car,因为它是Car的父级。Car是Vehicle的实现,所以Car就是车辆。你可以在这里阅读更多内容:https://www.tutorialspoint.com/What-is-Is-a-relationship-in-Java
发布于 2020-02-26 22:44:42
因为v是一个(具体的) Vehical (我想你是指vehicle)。
但Vehical的“具体”实例不是Car。它是Vehical的一个(非特定的)实例。所以v instanceof Car就是false。
但是c是Car的一个具体实例,因为Car是Vehical的子类,c也是一个Vehical,因为Car的所有实例也都是Vehical的实例。所以c instanceof Vehical是true,因为(在你的模型中)所有的‘Car’都是‘`Vehical’的(通过继承隐式地)。
如果您不希望存在不是更具体类型的Vehical的Vehical实例(例如Car、Motorbike?、Lorry?),则可以使Vehical成为一个抽象类。在现实世界中,不可能有一辆车不是一种特定的车。
胡说八道:,你开什么车?我开一辆车。什么样的交通工具?没什么特别的,它只是一辆车而已!
推荐的模型是声明一个名为Vehical的interface,并为每个(更多)具体类型的Vehical实现它,因为这种继承模型很难管理。但你所做的是正确的。
https://stackoverflow.com/questions/60416139
复制相似问题