ProgrammingHardProduct-company placement · Java

What is printed?

What is printed?
interface Named { default String n() { return getClass().getSimpleName(); } }
class Dog implements Named { }
// in main:
Named x = new Dog();
System.out.print(x.n());
  1. A. Named
  2. B. Object
  3. C. Dog
  4. D. Compile-time error: getClass() is not available in an interface

Correct answer: C. Dog

A default method runs on the actual object, so this.getClass() (Object's method, available to every object) returns the runtime class Dog.

More OOP with C++ and Java questions

Exams that ask this topic