Originally posted by saied ims:
1. class Dog { }
2. class Beagle extends Dog { }
3.
4. class Kennel {
5. public static void main(String [] arfs) {
6. Beagle b1 = new Beagle();
7. Dog dog1 = new Dog();
8. Dog dog2 = b1;
9. // insert code here why Beagle b4 = dog2; is illegal isnt dog2 refer to the object that b1 refer i mean the new beagle(); or no matter whats the object is ..
10. }
11. }
dog2 is a reference to an object of type Dog. You cannot make a reference to a Beagle equal to a reference to a Dog, because the Dog object might not be a Beagle.
The object could be a Poodle, a Basset Hound, etc.
A subclass object can always be referred to with a superclass reference.
But you cannot use a subclass reference to refer to a superclass object (unless the run-time type of the object is the subclass or one of its subclasses).