What is the output of the following Java code?
class Parent { void show() { System.out.println("Parent show"); } } class Child extends Parent { void show() { System.out.println("Child show"); } } public class Test { public static void main(String[] args) { Parent obj = new Child(); obj.show(); } }
Remember that method overriding uses the actual object's method, not the reference type's method.
The object obj is declared as Parent but created as Child. The show() method is overridden in Child. At runtime, the Child version is called, so it prints "Child show".
What will be printed when running this Java code?
class Parent { String name = "Parent"; } class Child extends Parent { String name = "Child"; } public class Test { public static void main(String[] args) { Parent obj = new Child(); System.out.println(obj.name); } }
Field access depends on the reference type, not the object type.
The variable obj is of type Parent. Field access uses the reference type, so obj.name accesses Parent's name field, printing "Parent".
What error will this Java code produce?
class Parent { Parent() { System.out.println("Parent constructor"); } } class Child extends Parent { Child() { this(); System.out.println("Child constructor"); } } public class Test { public static void main(String[] args) { new Child(); } }
Check how constructors call each other using this() and super().
The constructor Child() calls itself recursively with this(), causing a compile-time error for recursive constructor invocation.
What is the output of this Java program?
class Parent { void display() { System.out.println("Parent display"); } } class Child extends Parent { void display() { System.out.println("Child display"); } void show() { super.display(); display(); } } public class Test { public static void main(String[] args) { Child c = new Child(); c.show(); } }
super.display() calls the parent method, display() calls the child method.
The show() method calls super.display() which prints "Parent display", then calls display() which is overridden in Child and prints "Child display".
Consider this Java code:
class Parent {
Parent() {
System.out.println("Parent created");
}
}
class Child extends Parent {
Child() {
System.out.println("Child created");
}
}
public class Test {
public static void main(String[] args) {
Child c = new Child();
}
}How many objects are created when new Child() is executed?
Remember that a child object includes the parent part; only one object is created.
When new Child() runs, it creates one object of type Child. This object contains the parent part automatically. Constructors for both classes run, but only one object is created.