Java OCA OCP Practice Question 339

Question

What is the output of the following code?

1: public class Main { 
2:  public Main() { System.out.print("Main"); } 
3:  public Main(int age) { System.out.print("MainAge"); } 
4:  private boolean hasArea() { return false; } 
5:  public static void main(String[] args) { 
6:    Main deer = new SubMain(5); 
7:    System.out.println(","+deer.hasArea()); 
8:  } /* w  w w  .j a  va2s  . c o  m*/
9: } 
10: class SubMain extends Main { 
11:  public SubMain(int age) { System.out.print("SubMain"); } 
12:  public boolean hasArea() { return true; } 
13: }  
A.  MainSubMain,false 
B.  MainSubMain,true 
C.  SubMainMain,false 
D.  SubMainMain,true 
E.  MainAgeSubMain,false 
F.  MainAgeSubMain,true 
G.  The code will not compile because of line 7. 
H.  The code will not compile because of line 12. 


A.

Note

The code compiles and runs without issue, so options G and H are incorrect.

First, the SubMain object is instantiated using the constructor that takes an int value.

Since there is no explicit call to the parent constructor, the default no-argument super() is inserted as the first line of the constructor.

The output is then Main, followed by SubMain in the child constructor, so only options A and B can be correct.

Next, the method hasArea() looks like an overridden method, but it is actually a hidden method since it is declared private in the parent class.

Because the hidden method is referenced in the parent class, the parent version is used, so the code outputs false, and option A is the correct answer.




PreviousNext

Related