简体   繁体   中英

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 .
  2. Car is implementation of Vehicle , so Car is Vehicle.

You can read more here: https://www.tutorialspoint.com/What-is-Is-a-relationship-in-Java

Because v is a (concrete) Vehical (I think you mean vehicle).

But a 'concrete' instance of Vehical isn't a Car . It's a (non-specific) instance of Vehical . So v instanceof Car is 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 . So c instanceof Vehical is true because (in your model) all 'Car's are `Vehical's as well (implicitly by inheritance).

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 ?). 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. But what you've done is valid.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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