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);- A. true
- B. false
- C. Compilation error: Shape is not related to Colorable
- 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
- What is printed? java class Base implements Cloneable { int x = 5; @Override public Base clone() throws CloneNotSupportedException {…
- What is printed? java class Node<T extends Comparable<T>> { T value; Node(T v) { value = v; } boolean isGreaterThan(Node<T> other) {…
- What is printed? cpp struct Base { virtual void greet() const { cout << "Base "; } }; struct Derived : Base { void greet() const override…
- What is printed? cpp class Base { public: Base(const Base&) = delete; Base() = default; virtual void show() { cout << "Base"; } }; class…
- What is printed? java class Vehicle { void move() { System.out.print("Vehicle moves "); } } class Car extends Vehicle { @Override void…
- What is printed? java class Animal { String category() { return "Animal"; } } class Mammal extends Animal { @Override String category() {…