Java OCA OCP Practice Question 3195

Question

Which import statements, when inserted at (4) in package p3, will result in a program that can be compiled and run?.

package p2;/*from   ww w .  jav a  2s.c om*/
enum March {
  LEFT, RIGHT;                          // (1)
  public String toString() {
    return "Top-level enum";
  }
}
public class MyClass {
  public enum March {
    LEFT, RIGHT;                 // (2)
    public String toString() {
      return "Static enum";
    }
  }
  public enum Letter { 
    A, B;
    public static enum March {LEFT, RIGHT;        // (3)
      public String toString() {
        return "Statically nested enum";
      }
    }
  }
}
package p3;/*from  w w  w .j av  a 2 s .c  om*/
// (4) INSERT IMPORTS HERE
public class Main {
  public static void main(String[] args) {
    System.out.println(March.LEFT);
    System.out.println(MyClass.March.LEFT);
    System.out.println(p2.MyClass.March.LEFT);
    System.out.println(Letter.March.LEFT);
    System.out.println(MyClass.Letter.March.LEFT);
    System.out.println(p2.MyClass.Letter.March.LEFT);
    System.out.println(LEFT);
  }
}

Select the three correct answers.

(a) import p2.*;//  www  .ja  v a 2s .c  o  m
    import p2.MyClass.*;
    import static p2.MyClass.Letter.March.LEFT;

(b) import p2.*;
    import static p2.MyClass.*;
    import static p2.MyClass.Letter.March.LEFT;

(c) import p2.MyClass;
    import static p2.MyClass.*;
    import static p2.MyClass.Letter.March.LEFT;

(d) import static p2.MyClass;
    import static p2.MyClass.*;
    import static p2.MyClass.Letter.March.LEFT;

(e) import p2.*;
    import static p2.MyClass.*;
    import static p2.MyClass.Letter.*;

(f) import p2.*;
    import static p2.MyClass.*;
    import static p2.MyClass.Letter.March;


(a), (b), (c)

Note

First, note that nested packages or nested static members are not automatically imported.

In (d), p2.MyClass is not a static member and therefore cannot be imported statically.

With (e), March.LEFT becomes ambiguous because both the second and the third import statement statically import March.

The enum constant LEFT cannot be resolved either, as its enum type March cannot be resolved.

With (f), the enum constant LEFT cannot be resolved, as none of the static import statements specify it.

The enum type p2.March is also not visible outside the package.




PreviousNext

Related