Creating References Using Inheritance Hierarchies

AP Computer Science A· difficulty 3/5

public class Animal {}
public class Dog extends Animal {}
// Usage:
Animal[] arr = new Dog[3];
arr[0] = new Dog();
System.out.print(arr.length);

What is printed?

  • A

    0

  • B

    1

  • C

    3

    check_circle
  • D

    Compile error

Explanation

Java arrays are covariant: a Dog[] can be assigned to an Animal[] reference. arr.length is 3.

Want 10 more like this — adaptive to your weak spots?

Related questions