0

Would someone explain the concept of casting objects in Java and the usage of a subclass in place of a superclass? Also the usage of a superclass in place of a subclass?

I have read a few books and online material but I just don't get this concept for some reason...

For example if a have this class structure where object is the base class and Vehichle extends the object class. Then if we have 2 additional classes "Car" which extends "Vehichle" and "Motorcycle" which also extends vehicle. How does the object casting work? When would an explict cast be needed? When would the cast be implicit?

Object | Vehicle | Car - Motorcycle

Villumanati
  • 553
  • 2
  • 8
  • 17

2 Answers2

0

When you have two variables whose type is not a primitive and is different:

A a; 
B b;

If you want to assign a to b (b=a), you have to use an explicit cast if A is not a subclass of B. If A is a subclass of B, you may use an implicit cast. In your case:

Car c =new Car();
Motorcycle m=new Motorcycle();
Vehicle v=new Motorcycle();
v=c;//Implicit cast, because Car is a subclass of Vehicle;
c=(Car)v;//Explicit cast, because Vehicle is not a subclass of Car;
m=(Motorcycle)c;//Doesn't compile even with explicit cast because an instance referenced by a Car variable may never be referenced by a Motorcycle variable 
Andres
  • 10,561
  • 4
  • 45
  • 63
0

Casting from descendant to ancestor is implicit, in fact your are better off not viewing it as a cast at all. A motorcycle is a vehicle, so any method expecting vehicle will happily accept it.

Going in any other direction is problematic, and requires an explicit cast. You can tell the compiler your motorcycle is a car and it will believe you. Wheels.count will still work, Turn(Left) will still work (given they were defined in vehicle). As soon as you try and wind down the window things will start to go wrong....

View all explicit casts with extreme suspicion.

Tony Hopkinson
  • 20,172
  • 3
  • 31
  • 39