It is ok, if you try to assign Base class object to the derived class reference variable with casting. But it is ok for compile time. It will fail at run time. JVM recognizes that this is wrong you have done and compiler relied on you because it saw the cast.
Derived class ref variable can't hold the object of base class.
Hi two all.. Yeah i figured out my mistake...but have also found out the solution the answer to the problem is very well defined in K&B book you should look at page number 113 chapter 2 under reference variable casting and you will get the answer... In brief the answer can be stated as The object of the class Base does not know anything about the derived class untill the reference of it points to the the object of class derived since it has all the things a base contained hence the statement...
Derived d2= (Derived)new Base(); will compile but will produce an exception. Another senario like the above which will compile but will produce an exception is Base b= new Base(); Derived d= (Derived)b;//compile but will produce exception
This is a very good point about reference casting and must be carefully noted... good question indeed.