考虑以下代码:

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..
  }
}


在此,接口Vehicle和Car具有相同的常量TYPE,但值不同。

Line1的generalConcreteClass会产生歧义,因此必须进行类型转换,并且可以访问TYPE中的任何一个。

Line2:车辆对象具有“车辆”接口的引用。

第3行:如何将车辆对象转换为Car类型,并且仍访问Car的常量TYPE。车辆对象如何看得见。或者它是如何在内部工作的?

现在,如果我不让类实现Car接口,则类似的对车辆对象进行类型转换(类型为Car)将引发ClassCastException。

最佳答案

静态方法和字段不是多态的。您永远不要使用实例来访问静态字段。使用Vehicle.TYPECar.TYPE

如果要多态访问对象的类型,请使用getType()实例方法。

第3行不会引发ClassCastException,因为对象的具体类型是Main,而Main是Car,因此强制转换起作用。

09-30 14:23
查看更多