line 1 gives an error , because at compile time methods are associated with reference so compiler will search m() in to Parent class & ....
but in line 2 , we are casting a reference in to another reference ... whats the funda of casting reference : 1] sub class reference are implicitly casted into super class : super = sub ; // super & sub are reference of Parent & Child respectively .
2] when we cast super class reference into sub class .
3] can we cast any reference to other reference ( no relation b/w class )
thanks a lot . [ January 14, 2005: Message edited by: rathi ji ]
I guess hypothetically, a smart compiler may know that two types aren't related at all, and give you a compile-time error:
Although technically, you could have done:
... since at this point, it could have been possible that s was an Integer, i.e. Integer is related to Object. Anyways, I haven't really spent a whole lot of time casting completely unrelated objects, so this is just a bunch of rambling. There is the wonderful ClassCastException for those times when the compiler allows it, but it's bad at runtime.
Object conversion can be performed without explicit cast if it's an upcast (the object is being converted to a parent type or interface). This is because the subclass is guaranteed to contain at least the elements of the parent or interface without reducing access to members or throwing additional checked exceptions. However, explicit casting is required for the compiler to downcast, because a parent object does not necessarily contain the elements of a subclass.
Note that it's the object reference that's being cast or converted -- not the object itself. The true object type is set at instantiation via the new keyword. The type of a reference variable is known at compile time, but the object's true type cannot be known until runtime.
Upcast conversion is accomplished either by direct assignment or through method call (to fit the argument's type). If being converted to an interface, the original object must implement the interface to which it's being converted. (Thus, an Array can be converted to a Cloneable or Serializable interface, because Array implements these interfaces. An Array can also be converted to another Array of convertible object references.) Explicit casting for upcasts is legal, but unnecessary since conversion will be performed implicitly.
Explicit downcasting is accomplished by preceding the object being cast with the desired type in parentheses. In performing a downcast, the object's true runtime type must be consistent with the destination type -- i.e., it must have been previously upcast (e.g., to Object for storage in a Collection). If a cast is of an incorrect type, then the file will compile, but will throw a ClassCastException at runtime.
[ January 14, 2005: Message edited by: marc weber ]
"We're kind of on the level of crossword puzzle writers... And no one ever goes to them and gives them an award." ~Joe Strummer sscce.org