February 27, 2015

What is the Result of the Below Code Snippet ?

Given:

5. class Atom {
6. Atom() { System.out.print("atom "); }
7. }
8. class Rock extends Atom {
9. Rock(String type) { System.out.print(type); }
10. }
11. public class Mountain extends Rock {
12. Mountain() {
13. super("granite ");
14. new Rock("granite ");
15. }
16. public static void main(String[] a) { new Mountain(); }
17. }


A. Compilation fails.
B. atom granite
C. granite granite
D. atom granite granite
E. An exception is thrown at runtime.
F. atom granite atom granite







Answer: F


Explanation :

Inside Main Method new Mountain object is created which calls its constructor in Line 12.Inside Mountain constructor ,super("granite") calls the Rocks constructor by passing granite String argument.Inside Rock constructor ,implicitly calls super() Atom constructor passing no argument.

Therefore atom is printed first from the SOP of Atom Constructor,then comes down to Rock constructor and prints whats is stored in rocks constructor's variable (String Type) which is Granite .

Comes down and now a new Rock object gets created by calling constructor of Rock passing "granite" String argument and gets accepted in String type= "granite".Inside Rock constructor ,implicitly calls ( super() ) Atom constructor passing no argument.


Therefore atom is printed again ,then comes down to Rock constructor and prints whats is stored in type a String variable which is Granite.

Comes down to mountain method and comes back to main method and program terminates printing the result Atom Granite Atom Granite .option F.




Related Topics

0 comments:

Post a Comment