ProgrammingHardTCS NQT · Infosys pattern

What is printed?

What is printed?
abstract class Shape {
    abstract double area();
}
interface Colorable {
    String color();
}
class Circle extends Shape implements Colorable {
    double r;
    Circle(double r) { this.r = r; }
    double area() { return Math.PI * r * r; }
    public String color() { return "red"; }
}
// in main:
Shape s = new Circle(2);
System.out.println(s instanceof Colorable);
  1. A. true
  2. B. false
  3. C. Compilation error: Shape is not related to Colorable
  4. D. Compilation error: instanceof cannot check an interface

Correct answer: A. true

Java allows instanceof checks against any reference type that the actual object could potentially satisfy; the runtime object is a Circle, which does implement Colorable, so the check compiles and evaluates to true, regardless of s's declared type being the unrelated class Shape.

More OOP with C++ and Java questions

Exams that ask this topic