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" .
Mohit sold 5 pens making a 8% profit on each and another 15 pens making a 12% profit on each. If the total selling price for all 20 pens was ₹555, wha...
- Cost price of article ‘B’ is (250/7)% of selling price of article ‘A’. Article ‘A’ is sold at 40% profit and cost price of article ‘A’ is R...
A shopkeeper sold two items. The selling price of the first item equal the cost price of the second item. He sold the first item at a profit of 20% and ...
Ajay buys an old desktop for Rs. 6200 and spends Rs. 400 on its repairs. If he sells the desktop for Rs. 7000, his gain percent is
By selling a Mobile for Rs. 3720 a shopkeeper gains 24%. If the profit reduced to 14%, then the selling price will be
- Ravi sold a gadget to Prashant with a 15% profit. Prashant then sold it to Rina, earning the same absolute profit (in Rs.) that Ravi made. Finally, Rina so...
A shopkeeper loses 15% by selling article A for Rs 212.50 and gains 35% by selling article B for Rs 1012.50. What is his overall gain percentage in the ...
Pankaj purchased a machine for Rs. 79,000 and spent Rs. 4000 on repair and Rs. 3000 on transport and sold it with 25% profit. At what price did he sell ...
A dishonest dealer professes to sell his goods at cost price, but he uses a weight of 600 gm for the kg weight. Find his gain per cent.
A man bought 5 articles K, L, M, N, O at Rs. 620 each. Selling prices of K,L, M,N and O were x, x+ 20, x +25, x +75, x +80 respectively. Overall profit ...