Java OCA OCP Practice Question 2641

Question

Given:

2. class Shape {  
3.   String hands = "15";  
4. }  /*from w ww  .  j a  va2s  . c  om*/
5. class Main extends Shape {    
6.   static String hands = "14";  
7.   public static void main(String[] args) {  
8.     String hands = "13.2";  
9.     String result = new Main().getSize(hands);  
10.     System.out.println(" " + result);  
11.   }  
12.   String getSize(String s) {  
13.     System.out.print("hands: " + s);  
14.     return hands;  
15.   } 
16. } 

What is the result?

  • A. 14
  • B. 15
  • C. hands: 13.2 14
  • D. hands: 13.2 15
  • E. Compilation fails.
  • F. An exception is thrown at runtime.


C is correct.

Note

This code shows a kind of variable "shadowing."

In the getSize() method, the question is whether to use the class's static "hands" variable, or to use the superclass's instance "hands" variable.

The variable in the same class is used.




PreviousNext

Related