[英]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
不是Car
因為它是Car
父級。Car
是Vehicle
實現,所以 Car 就是 Vehicle。您可以在此處閱讀更多信息: https : //www.tutorialspoint.com/What-is-Is-a-relationship-in-Java
由於v
是一個(具體的) Vehical
(我想你指的車輛)。
但是Vehical
的“具體”實例不是Car
。 它是Vehical
的(非特定)實例。 所以v instanceof Car
是false
。
但是c
是Car
的具體實例,因為Car
是Vehical
的子類c
也是Vehical
因為Car
所有實例也是Vehical
實例。 所以c instanceof Vehical
是true
因為(在你的模型中)所有的“汽車”也是“汽車”(隱式繼承)。
如果您不希望Vehical
實例不是更具體的Vehical
類型(例如Car
、 Motorbike
?、 Lorry
?),您可以將Vehical
抽象類。 在現實世界中,永遠不會有不是特定類型車輛的車輛。
廢話:你開什么車? 我開車。 什么樣的車輛? 沒有什么特別的,就是一輛車!
推薦的模型是聲明一個名為Vehical
的interface
,並為每個(更多)具體類型的Vehical
實現它,因為這種繼承模型可能難以管理。 但你所做的是有效的。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.