Java casting with reference to a superclass

Can someone explain what is going on here?

Assume that Carand Bikeare subclasses Vehicle.

It seems to me that the Vehicle vlink is being passed in Bike. I know this is illegal and indeed the compiler spits out ... Car cannot be cast to Bike.

But should this not be Vehicleattributable to Bike? In the end, Vehicle vis a link Vehicle.

public class Test {
   public static void main(String[] args) {
       Vehicle v = new Car();
       Bike b = (Bike) v;
       // some stuff
    }   
}
+5
source share
5 answers

Car, . (, ), , .

, Vehicle, , .

+3

Car. v Vehicle, Vehicle v = new Car(); , a Car Vehicle.

v ; Car. , Car Bike.

+1

Bike b = (Bike) v;

, , , v Vehicle. , . , - b - , , , v Bike Car.

0

A () :

"" , (), , ().

, , , , , .

, :

ArrayList<Vehicle> vehicles = new ArrayList<Vehicle>();
vehicles.add(new Bike());
vehicles.add(new Car());
vehicles.add(new Bike());

//Some other crazy code

for(Vehicle v : vehicles) {
    v.applyBrakes();
    v.changeDownGear();
    v.turnRight();
}

Vehicle (Bike, Car, Segway ..)

0

, , . , , :

    Vehicle
       |
  __________
  |         |
 Car      Bike

, Car Bike Vehicle, , Vehicle Car Bike. Java . , Car , Vehicle. Bike. , Car Bike, . Cars Vehicles, Vehicles Cars. Bikes. Car Bike .

You do this to create more extensible code. For example, you can write code that understands how to interact with code that will be written in the future. An example of this is some common interface, for example drive(), which allows other developers to later provide custom implementations. Your code, although written before it, can still work with it, because it can handle new subclasses as if they were instances of a base class.

0
source

All Articles