nerdexam
Oracle

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).

Working with Inheritance

Question

Given: 1. interface Pet { } 2. class Dog implements Pet { } 3. class Beagle extends Dog { } Which three are valid?

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)
  • A
    86% (37)
  • B
    9% (4)
  • C
    2% (1)
  • F
    2% (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).

APet a = new Dog();Correct

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.

BPet b = new Pet();

Interfaces cannot be instantiated directly using the `new` keyword; they must be implemented by a concrete class.

CDog f = new Pet();

You cannot assign an interface type directly to a concrete class reference without an explicit cast, and `new Pet()` is invalid anyway.

DDog d = new Beagle();Correct

A `Dog` superclass reference can point to an object of its `Beagle` subclass, which is a valid form of upcasting.

EPet e = new Beagle();Correct

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`.

FBeagle c = new Dog();

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

#interfaces#inheritance#polymorphism#type compatibility

Community Discussion

No community discussion yet for this question.

Full 1Z0-803 Practice