1Z0-803 · Question #106
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();. Valid assignments in Java inheritance follow the 'is-a' principle, allowing a reference of a supertype (interface or superclass) to hold an object of a subtype (implementing class or subclass).
Question
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
(43 responses)- A86% (37)
- B9% (4)
- C2% (1)
- F2% (1)
Why each option
Valid assignments in Java inheritance follow the 'is-a' principle, allowing a reference of a supertype (interface or superclass) to hold an object of a subtype (implementing class or subclass).
A `Pet` interface reference can point to an object of a class (`Dog`) that implements the `Pet` interface, which is a valid form of polymorphism.
Interfaces cannot be instantiated directly using the `new` keyword; they must be implemented by a concrete class.
You cannot assign an interface type directly to a concrete class reference without an explicit cast, and `new Pet()` is invalid anyway.
A `Dog` superclass reference can point to an object of its `Beagle` subclass, which is a valid form of upcasting.
A `Pet` interface reference can point to an object of the `Beagle` class because `Beagle` extends `Dog`, and `Dog` implements `Pet`, making `Beagle` implicitly a `Pet`.
A subclass reference (`Beagle`) cannot directly hold an object of its superclass (`Dog`) without an explicit cast, which would also likely result in a `ClassCastException` at runtime.
Concept tested: Java inheritance, interfaces, polymorphism, type casting
Source: https://docs.oracle.com/javase/tutorial/java/IandI/polymorphism.html
Topics
Community Discussion
No community discussion yet for this question.