Java OCA OCP Practice Question 796

Question

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

//in file /root/com/mypkg/MyClass .java 
package com.mypkg; 
public class MyClass{ 
  public static int MyId = 10; 
  public void apply (int i){ 
    System .out.println ("applied"); 
   } //from   w  w  w. j a  va 2 s. co m
} 

//in file /root/com/mypkg2/Main .java 
package com.mypkg2; 
//1 <== INSERT STATEMENT (s) HERE 
public class Main{ 
    public static void main (String [] args){ 
       MyClass x = new MyClass (); 
       x .apply (MyId); 
     } 
} 

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

Select 2 options

  • A. import static MyClass;
  • B. import static com .mypkg.*;
  • C. import static com .mypkg.MyClass .*;
  • D. import com .mypkg.*;
  • E. import com .mypkg.MyClass .MyId;


Correct Options are  : C D

Note

For Option B. import static com .mypkg.*;

Bad syntax. com.mypkg is a package and you cannot import a package statically.

You can only import static members of a class statically.

For Option C. import static com .mypkg.MyClass .*;

This static import is required because of Main is accessing MyId directly without its class name ( i.e. MyClass.MyId).

For Option D. import com .mypkg.*;

This is required because Main also accesses the class MyClass : MyClass x = new MyClass ();

If Main had only one statement, System .out.println (MyId); import static com .mypkg.MyClass .* would suffice.

E. import com .mypkg.MyClass .MyId;

Syntax for importing static fields is:

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



PreviousNext

Related