简体   繁体   English

陈述 3 是错误的,而陈述 4 是正确的

[英]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);
    }
}
  1. Vehicle isn't a Car because it is parent for a Car . Vehicle不是Car因为它是Car父级。
  2. Car is implementation of Vehicle , so Car is Vehicle. CarVehicle实现,所以 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 Carfalse

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 .但是cCar的具体实例,因为CarVehical的子类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 Vehicaltrue因为(在你的模型中)所有的“汽车”也是“汽车”(隐式继承)。

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类型(例如CarMotorbike ?、 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.推荐的模型是声明一个名为Vehicalinterface ,并为每个(更多)具体类型的Vehical实现它,因为这种继承模型可能难以管理。 But what you've done is valid.但你所做的是有效的。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM