Java 陈述3如何为假,陈述4如何为真 车辆不是汽车,因为它是汽车的父级 Car是Vehicle的实现,所以Car就是Vehicle
您可以在此处阅读更多内容:Java 陈述3如何为假,陈述4如何为真 车辆不是汽车,因为它是汽车的父级 Car是Vehicle的实现,所以Car就是Vehicle,java,inheritance,subclass,instanceof,Java,Inheritance,Subclass,Instanceof,您可以在此处阅读更多内容: 因为v是一种(具体的)车辆(我想你指的是车辆) 但是Vehical的“具体”实例不是Car。它是Vehical的(非特定)实例。所以汽车的v实例是false 但是c是Car的一个具体实例,因为Car的一个子类Vehical也是Vehical,因为Car的所有实例也是Vehical的实例。所以c instanceof Vehical是true,因为(在您的模型中)所有的“Car”也是“Vehical”(通过继承隐式地) 如果不希望存在不是更具体类型的车辆(例如汽车,摩托
因为
v
是一种(具体的)车辆(我想你指的是车辆)
但是Vehical
的“具体”实例不是Car
。它是Vehical
的(非特定)实例。所以汽车的v实例
是false
但是c
是Car
的一个具体实例,因为Car
的一个子类Vehical
也是Vehical
,因为Car
的所有实例也是Vehical
的实例。所以c instanceof Vehical
是true
,因为(在您的模型中)所有的“Car”也是“Vehical”(通过继承隐式地)
如果不希望存在不是更具体类型的车辆(例如汽车,摩托车,卡车),则可以将车辆设为抽象类。在现实世界中,任何车辆都不可能不是特定类型的车辆
胡说:你开什么车?我开车。什么样的车?没什么特别的,只是一辆车
建议的模型是声明一个名为Vehical
的接口
,并为每个(更多)具体类型的Vehical
实现它,因为这种继承模型可能难以管理。但是你所做的是有效的。所有Car
s都是Vehical
s。不是所有的Vehical
s都是Car
s.Car
扩展Vehical
,Vehical
没有扩展Car
你期望什么,为什么?旁注,它是拼写Vehicle,不是Vehical。@ElliottFrisch,那是相反的
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);
}
}