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" .
A, B and C are three pipes connected to a tank. A and B together fill the tank in 30 hours, B and C together fill the tank in 40 hours. A and C together...
Three pipe P1, P2 and P3 fill the tank in 15 hours, 10 hours and 20 hours respectively. If all the three pipes opened together and pipe P2 & P1 are clo...
- Pipe C can fill a tank in 10 hours and pipe D in 15 hours. If both the pipes are opened in an empty tank, how much time will they take to fill it?
Pipe ‘P’ alone can fill a tank in 12 hours. When pipe ‘P’ and ‘Q’ are opened together, they can fill 75% of the same tank in 9 hours. Find t...
Pipe A and Pipe B could fill a tank together in 30 hours and 20 hours respectively, while pipe C could empty it in 12 hours. If both inlet pipes are ope...
Tap A is 200% more efficient than tap B. Both the taps together can fill the tank in 6 hours. Find the time taken by tap C, which is 100% more efficien...
Pipe ‘A’ and pipe ‘B’ can fill a cistern in 10 minutes and 12 minutes respectively. Pipe ‘C’ alone can empty the cistern in 12 minutes. If a...
A tank has two inlet pipes, A and B, and one outlet pipe, C. Pipe A can fill the tank in 6 hours, and pipe B can fill the tank in 8 hours. Pipe C can em...
P, Q and R three pipes connected to a tank. P and Q together fill the tank in 30 hours, Q and R together fill the tank in 40 hours. P and R together fil...
Tap ‘A’ and tap ‘B’ can fill a tank in 48 hours and 30 hours, respectively. If both taps are opened together, then find the time after which tap...