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);
}
}

- 3,603
- 4
- 26
- 37

- 17
- 5
-
2All `Car`s are `Vehical`s. Not all `Vehical`s are `Car`s. – Eran Feb 26 '20 at 14:30
-
`Car`extends `Vehical`, `Vehical`doesn't extends `Car` – jhamon Feb 26 '20 at 14:30
-
What did you expect and why? – Amongalen Feb 26 '20 at 14:30
-
Sidenote, it's spelled Vehicle, not Vehical. – Amongalen Feb 26 '20 at 14:31
-
@ElliottFrisch, that's the opposite – jhamon Feb 26 '20 at 14:32
-
@jhamon Need more coffee. – Elliott Frisch Feb 26 '20 at 14:33
-
*Vehicles include wagons, bicycles, motor vehicles (motorcycles, cars, trucks, buses), railed vehicles (trains, trams), watercraft (ships, boats), amphibious vehicles (screw-propelled vehicle, hovercraft), aircraft (airplanes, helicopters) and spacecraft.* (wiki) Define more subclasses and you will see `v instanceof Car` doesn't always hold true – Andrew Tobilko Feb 26 '20 at 14:36
2 Answers
Vehicle
isn't aCar
because it is parent for aCar
.Car
is implementation ofVehicle
, so Car is Vehicle.
You can read more here: https://www.tutorialspoint.com/What-is-Is-a-relationship-in-Java

- 142
- 9
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
(e.g. 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.

- 8,165
- 2
- 13
- 35