Java OCA OCP Practice Question 1057

Question

Consider the following two classes defined in two .java files.

//in file /root/com/foo/X.java 
package com .foo; 
public class X{ 
  public static int MyID = 10; 
  public void apply (int i){ 
    System.out.println ("applied"); 
   } //ww  w  .  j  a  v a  2 s.c  om
} 

//in file /root/com/bar/Y.java 
package com .bar; 
//1  <== INSERT STATEMENT (s) HERE 
public class Y{ 
    public static void main (String [] args){ 
       System.out.println (X.MyID); 
     } 
} 

What should be inserted at // 1 so that Y.java can compile without any error?

Select 1 option

A. import static X; 
B. import static com.foo.*; 
C. import static com.foo.X .*; 
D. import com .foo.*; 
E. import com .foo.X .MyID; 


Correct Option is  : D

Note

A. and B. are wrong.

Bad syntax. Package import does not use static keyword.

C. is wrong.

This static import, although syntactically correct, will not help here because Y is accessing class X in X.MyID.

D. is correct. This is required because Y is accessing class X.

static import of MyID is NOT required because Y is accessing MyID through X ( X.MyID).

Had it been j ust System.out.println(MyID), only one import statement: import static com.foo.X.*; would have worked.

E. is wrong. Bad Syntax.

Syntax for importing static fields is: import static <package>.

<classname>.*; or import static <package>.<classname>.<fieldname>;




PreviousNext

Related