ProgrammingHardAmazon/Microsoft SDE MCQ · Java placement
What is printed?
What is printed?
abstract class Shape {
Shape() { System.out.print(area() + " "); }
abstract double area();
}
class Sq extends Shape {
double s = 2;
Sq() { System.out.print(area()); }
double area() { return s * s; }
}
// in main:
new Sq();- A. 4.0 4.0
- B. 0.0 4.0
- C. 0.0 0.0
- D. Compile error: abstract call in constructor
Correct answer: B. 0.0 4.0
Shape's constructor runs before Sq's field initialiser, so the overriding area() sees s = 0.0 and prints 0.0. Then s = 2 is set and Sq's constructor prints 4.0. Calling an abstract method from a constructor compiles; it is just dangerous.
More OOP with C++ and Java questions
- What is printed? java List<Integer> l = new ArrayList<>(List.of(5, 6, 7)); Iterator<Integer> it = l.iterator(); while (it.hasNext()) if…
- What does this Java program print? class A { String n = "A"; String get() { return n; } } class B extends A { String n = "B"; String get()…
- What does this Java program print? class P { P() { init(); } void init() { System.out.print("P "); } } class C extends P { int x = 5; C()…
- What does this Java code print? Integer a = 127, b = 127, c = 128, d = 128; System.out.println((a == b) + " " + (c == d) + " " +…
- What does this Java code print? class A { String n = "A"; String get() { return n; } } class B extends A { String n = "B"; String get() {…
- What does this Java program print? class P { static { System.out.print("1"); } { System.out.print("2"); } P() { System.out.print("3"); } }…