🎙 Free live masterclass · Sun, 29 Nov, 7:00 pm IST · Java Full Stack roadmap Register free →
Skills101
← Quiz: Inheritance and Polymorphism: all 10 questions

Quiz: Inheritance and Polymorphism · Question 7 of 10

What does this print? (code)

What does this print?

class A { String name = "A"; }
class B extends A { String name = "B"; }
public class Main {
    public static void main(String[] args) {
        A obj = new B();
        System.out.println(obj.name);
    }
}
  1. A.A
  2. B.B
  3. C.AB
  4. D.Compile error
Answer & explanation

Correct answer: A

Fields are not overridden. Which field is used depends on the variable's declared type (A), not the object's type. Only methods are polymorphic.

Can you get the rest right without peeking?

Take the timed Quiz: Inheritance and Polymorphism quiz free. Pass it to earn XP and count towards your certificate.

Start the quiz →