Reputation: 2391
Consider the following code :
public class Main implements Vehicle, Car {
public static void main(String[] args) {
Main generalConcreteClass = new Main();
System.out.println(((Vehicle) generalConcreteClass).TYPE); //**Line 1**
Vehicle vehicle = new Main(); //**Line 2**
System.out.println(vehicle.TYPE);// Here there is no Ambiguity since vehicle is of TYPE vehicle
System.out.println(((Car)vehicle).TYPE); // **Line3** This doesn't throw ClassCastException..
}
}
Here, both the interfaces Vehicle and Car have the same constant TYPE with different value.
There will be ambiguity with generalConcreteClass at Line1, so type-cast is necessary and any one of TYPE can be accessed.
Line2 : vehicle object has reference of Vehicle interface.
Line3 : How can I cast my vehicle object to Car type and still access the constant TYPE of Car. How is becomes visible to vehicle object. Or how does it work internally??
Now, if I dont make my class implement Car interface, then a similar type-casting of vehicle object to type Car throws a ClassCastException.
Upvotes: 0
Views: 96
Reputation: 691715
Static methods and fields are not polymorphic. You should never use an instance to access a static field. Use Vehicle.TYPE
or Car.TYPE
.
If you want to access the type of an object polymorphically, then use a getType()
instance method.
Line 3 doesn't throw a ClassCastException because the object's concrete type is Main, and a Main is a Car, so casting works.
Upvotes: 5