Why reference variable of type object must be cast when used as other object type

前端 未结 4 1210
一向
一向 2021-01-03 12:08

Although all classes in Java are sub-classes of Object class, but different from other object types, a reference variable of type Object can\'t be assigned to any other refe

4条回答
  •  星月不相逢
    2021-01-03 12:45

    Since Scream() is not declared as a public method of Object, you can't call it on a variable of type Object. The compiler only knows the static type of variables (references), so it can't tell nor verify that this reference is going to point to an object of type Tiger at runtime (which would be its dynamic type). This is why you get a compilation error.

    You may say it would be trivial for the compiler to verify the dynamic type in the case above, which is more or less correct. However, in real life, it is usually not so simple. Consider

    Factory factory = new SomeFactory();
    Object obj = factory.getProduct(param);
    // What is obj's dynamic type?
    

    The compiler could in theory detect that factory's dynamic type is SomeFactory. Then all it should do is to statically analyse the code within SomeFactory.getProduct() to detect the type of the product returned. Of course, getProduct may return different types of actual products depending on its parameters. So the compiler would need to detect the possible value(s) of param at the point of invocation... Which may come from any number of sources, e.g. user input, config file, DB... But even if this was all surmountable, the concrete product class may be loaded dynamically by the class loader at runtime, from a jar file which may not even be available at compile time. So the compiler may not even be aware of the existence of this specific class, much less of its public interface.

提交回复
热议问题