nerdexam
Oracle

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…

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

(30 responses)
  • A
    83% (25)
  • B
    3% (1)
  • C
    3% (1)
  • F
    10% (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

#Inheritance#Polymorphism#Interface Implementation#Type Compatibility

Community Discussion

No community discussion yet for this question.

Full 1Z0-808 Practice