[英]How statement 3 is false and 4 true
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);
}
}
Vehicle
isn't a Car
because it is parent for a Car
. Vehicle
不是Car
因为它是Car
父级。Car
is implementation of Vehicle
, so Car is Vehicle. Car
是Vehicle
实现,所以 Car 就是 Vehicle。You can read more here: https://www.tutorialspoint.com/What-is-Is-a-relationship-in-Java您可以在此处阅读更多信息: https : //www.tutorialspoint.com/What-is-Is-a-relationship-in-Java
Because v
is a (concrete) Vehical
(I think you mean vehicle).由于v
是一个(具体的) Vehical
(我想你指的车辆)。
But a 'concrete' instance of Vehical
isn't a Car
.但是Vehical
的“具体”实例不是Car
。 It's a (non-specific) instance of Vehical
.它是Vehical
的(非特定)实例。 So v instanceof Car
is false
.所以v instanceof Car
是false
。
But c
is a concrete instance of Car
and because Car
a sub-class of Vehical
c
is also a Vehical
because all instances of Car
are also instances of Vehical
.但是c
是Car
的具体实例,因为Car
是Vehical
的子类c
也是Vehical
因为Car
所有实例也是Vehical
实例。 So c instanceof Vehical
is true
because (in your model) all 'Car's are `Vehical's as well (implicitly by inheritance).所以c instanceof Vehical
是true
因为(在你的模型中)所有的“汽车”也是“汽车”(隐式继承)。
You can make Vehical
an abstract class if you don't want instances of Vehical
to exist that are not a more specific type of Vehical
(eg Car
, Motorbike
?, Lorry
?).如果您不希望Vehical
实例不是更具体的Vehical
类型(例如Car
、 Motorbike
?、 Lorry
?),您可以将Vehical
抽象类。 In the real world there could never be a vehicle that isn't a specific kind of vehicle.在现实世界中,永远不会有不是特定类型车辆的车辆。
Nonsense: What do you drive?废话:你开什么车? I drive a vehicle.我开车。 What kind of vehicle?什么样的车辆? No particular kind, it's just a vehicle!没有什么特别的,就是一辆车!
The recommended model would be to declare an interface
called Vehical
and implement it for each (more) concrete type of Vehical
because this inheritance model can difficult to manage.推荐的模型是声明一个名为Vehical
的interface
,并为每个(更多)具体类型的Vehical
实现它,因为这种继承模型可能难以管理。 But what you've done is valid.但你所做的是有效的。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.