i have a question about practical use of this example, when you are creating a variable of type derived class to store a variable of base class object.
DerivedClass C = new BaseClass();
in what case i can use this.
in what case i can use this.
You can't. Ever.
The main point of static typing is so that you can rely on the value of a variable being compatible with the type you've declared. So if you declare a variable as:
DerivedClass C;
then any value for C
must be able to be treated as a DerivedClass
. In particular, all the members of DerivedClass
must be available. That simply wouldn't be the case if the value is actually a reference to an instance of BaseClass
which doesn't have all those members.
Fortunately the language rules (and therefore the compiler) understand that this would be a Very Bad Thing and so you'll get a compile-time error.
See more on this question at Stackoverflow