posted 22 years ago
Hi, Howard. You have to differentiate an object reference from the object that it refers to, because they can be of different types. Sort of.
Suppose I declare
Base b
b is an object reference that can refer, or point to an object which is of type B or any of its subclasses. So I can do this:
b = new Base();
b = new Sub();
b = new Sub2();
Casting only affects the object references, not the objects being referred to. We can do this
Sub s = new Sub();
Base b = s;
This is considered a widening conversion, and no explicit cast is required.
We can also do this, provided we make an explicit cast
Base b = new Base();
Sub s = (Sub) b;
This is a narrowing conversion. This will compile, but will throw an exception at runtime, because the object being referred to by b is an object of type Base, and the object reference s can only point to objects of type Sub or its subclasses.
If it had been
Base b = new Sub();
Sub s = (Sub) b;
then it will work. The object referred to by b is really of type Sub, so s can "hold" it.
[ August 07, 2002: Message edited by: Anthony Villanueva ]