128k views
3 votes
What is the output of the following code?

public class Test1 {
public static void main(String[] args) {
ChildClass c = new ChildClass();
c.print();
}
}

class ParentClass {
int id = 1;
void print() {
System.out.println(id);
}
}

class ChildClass extends ParentClass {
int id = 2;
}


A. 0
B. 1
C. 2
D. Nothing

1 Answer

5 votes

Final answer:

Option C: The output of the given code is 2 because the print() method from ParentClass is inherited by ChildClass and it accesses the id of ParentClass.

Step-by-step explanation:

The output of the given code is C. 2. When the print() method is called on an instance of ChildClass, it inherits the print() method from its superclass, ParentClass, because ChildClass does not override the print() method. Therefore, the print() method of ParentClass is executed, and the field id of ParentClass is accessed, which has the value of 1.

The output of the code will be 2.

The code creates an instance of the ChildClass called c and then calls the print() method on it. Since the ChildClass extends the ParentClass, it inherits the print() method from the parent class.

However, the ChildClass also has its own id variable, which overrides the id variable from the parent class. So when the print() method is called, it accesses the id variable from the ChildClass, which is 2.

User Dipak Narigara
by
8.3k points