Question
What will be the output of the following Java snippet?
class A { Â Â Â public void display() { Â Â Â Â Â Â Â System.out.println("Class A"); Â Â Â }} class B extends A { Â Â Â public void display() { Â Â Â Â Â Â Â System.out.println("Class B"); Â Â Â }} public class Test { Â Â Â public static void main(String[] args) { Â Â Â Â Â Â Â A obj = new B(); Â Â Â Â Â Â Â obj.display(); Â Â Â }}Solution
This program demonstrates runtime polymorphism in Java through method overriding. When the method display() is called on the object obj, the overridden method in class B is executed. This is because obj is instantiated as new B(), and at runtime, the JVM determines the appropriate method to execute based on the actual type of the object. Thus, even though obj is declared as type A, the overridden display() method in B is executed, producing the output "Class B" . This behavior is a key feature of Java's dynamic method dispatch mechanism. Explanation of Incorrect Options: A) Class A : This would be true if the display() method in class B was not overridden. However, since B overrides A's method, this option is incorrect. C) Compilation Error : The code is syntactically correct, so it compiles without any issues. D) Runtime Error : The program runs successfully, as all method calls are valid and properly resolved at runtime. E) None of the above : This is incorrect, as the correct output is explicitly "Class B" .
Average run scored by a batsman in first ‘x’ matches is 20. In next 5 matches he scored runs with an average of 60 so that his overall average incre...
In a company, the average number of employees named Amit and Chinky is 25. The number of Chinky's name employees is 50% higher than the number of Amit's...
Of the four numbers, whose average is 75, the first is one-fourth of the sum of the last three. The first number is
- A class of 20 students has an average age of 19 years. 5 new students join and the average becomes 17.5 years. Find the average age of the new students.
The average value of the property of Ravi, Sanjay, and Deepak is Rs. 75 lacs. The value of the property of Ravi is Rs. 20 lacs less than the value of th...
- The average of two numbers is 5 more than the smaller number among them. If the greater number is 60% more than the smaller number, then find the sum of th...
There are only 220 students living in hostel. If 20 students left hostel, then overall expenditure of mess is reduced by Rs. 800 weekly but per student ...
The average weight of 7 boxes P, Q, R, S, T, U and V is 72kg. Another box A is added to group and the average now becomes 70kg. If another box C whose ...
- In a company team, if 3 employees each weighing 65 kg resign, the average weight of the remaining team members drops by 1 kg. But if 4 employees with an av...
The average cost of 3 chairs is Rs. 10000. The average cost decrease by 22% when one more chair is included. What is the cost price of the 4th