The Rule is
A Super Reference Variable can refer a Subclass Object.
SuperClass s = new SubClass(); //Subclass extends SuperClass is valid
the otherway isn't valid ie SubClass sb = new SuperClass()
Comin to Object Ref Casting..
Consider this Scenario
Class Citrus extends Fruit
Class Orange extends Citrus
Class Lemon extends Citrus
public static void main(String args)
o=new Orange();//Object created, call it as O1
c=o;//perfectly valid going by rule, c now refers to O1
f=o; //perfectly valid Its nothing but c=o; followed f=c;
// f now refers to O1
l=o; //not valid, since l is not Superclass of o, this is called sidecasting
//This is casting, in this case both sides are of type Lemon hence no compile time error, But There will be a Runtime Exception because both classes are incompatible
or = (Orange)f; //No compile time error as explained above
// There will be no Runtime Exception also, It's like this...
f is containing a reference to O1 (Orange Object), u r trying to assign that reference to o1 which is also of type Orange.
I hope that sounds logically correct.