Sometimes downcasting is useful because the data comes from code that cannot know its actual type. Consider this example from the Hibernate interceptor interface
public void onDelete(Object entity, Serializable id, Object[] state, String[] propertyNames, Type[] types) {
Note that entity is typed as Object , although this is by far the more specific type. Hibernate may not have a compilation reference for the types of objects it stores, but this can still be a useful method:
if (entity instanceof Auditable) { Auditable data = (Auditable)entity; // downcast logger.warn("{current user} is deleting " data.GetDescriptionForAudit()); }
In this example, casting is inevitable - the Hibernate API cannot be improved, Object is the best type that can be used.
In the case of the swing paint method, it seems that the method signature was supposed to use Graphics2D , otherwise the methods you needed should be defined in the Graphics class. Perhaps the swing designers are trying to say "not dependent on Graphics2D methods if you really need it."
To answer the question
Downcasting is allowed because sometimes a programmer has to do this. In the Hibernate example, the API is typed as well as it can be. In the swing example, it can be argued that the API has a flaw. But in any case, it is useful for Java to allow downcasting.
source share