1Z0-808 · Question #89
Given: 1. interface Pet { } 2. class Dog implements Pet { } 3. class Beagle extends Dog { } Which three are valid?
The correct answer is A. Pet a = new Dog(); D. Dog d = new Beagle(); E. Pet e = new Beagle(). A, D, and E are valid because Java allows implicit upcasting - you can assign an object to any reference type that is a supertype in its hierarchy. Dog implements Pet (A), Beagle extends Dog (D), and Beagle also transitively satisfies Pet through its parent chain (E). In all…
Question
- interface Pet { }
- class Dog implements Pet { }
- class Beagle extends Dog { }
Options
- APet a = new Dog();
- BPet b = new Pet();
- CDog f = new Pet();
- DDog d = new Beagle();
- EPet e = new Beagle();
- FBeagle c = new Dog();
How the community answered
(30 responses)- A83% (25)
- B3% (1)
- C3% (1)
- F10% (3)
Explanation
A, D, and E are valid because Java allows implicit upcasting - you can assign an object to any reference type that is a supertype in its hierarchy. Dog implements Pet (A), Beagle extends Dog (D), and Beagle also transitively satisfies Pet through its parent chain (E). In all three, the right-hand side is a subtype of the left-hand side.
The distractors fail for distinct reasons: B is invalid because Pet is an interface and interfaces cannot be instantiated with new. C fails on two counts - same instantiation problem, plus Dog is a subtype of Pet, not a supertype, so a Dog variable cannot hold a Pet reference without an explicit cast. F attempts a downcast (Beagle c = new Dog()) without casting - the compiler won't allow assigning a broader type (Dog) to a narrower reference (Beagle) implicitly.
Memory tip: Think of the hierarchy as a pyramid (Pet → Dog → Beagle). You can always point a higher reference at a lower object (upcast = safe, implicit), but never point a lower reference at a higher object without an explicit cast - and you can never instantiate an interface at all.
Topics
Community Discussion
No community discussion yet for this question.