#570 – Assignment Compatibility for Reference Types
April 26, 2012 2 Comments
A reference type is assignment compatible if the value being assigned belongs to a type that is either the same as, or is a derived type of, the type of the storage location being assigned to. You can assign a variable of type T to a storage location of type U if T is a narrower type than U, or is the same type as U.
Hound huck = new Hound("Huckleberry", 55); // Since Hound is a sub-class of Dog, we can // assign to a variable of type Dog Dog dog1 = huck;
In this case, the variable of type Dog will still be pointing to an instance of a Hound. The assignment doesn’t change anything about the object.
To see this, construct an instance of a Dog directly and then compare the objects.
// This one points to an actual Dog instance Dog dog2 = new Dog("Just some dog", 2);