Java OCA OCP Practice Question 1954

Question

Given the declaration.

interface MyValue { int getInt(); }

which of the following methods are valid?.

//----(1)----//ww w.  j  av a 2 s  .  c  o  m
  MyValue makeMyValue(int i) {
    return new MyValue() {
      public int getInt() { return i; }
    };
  }
//----(2)----
  MyValue makeMyValue(final int i) {
    return new MyValue {
      public int getInt() { return i; }
    };
  }
//----(3)----
  MyValue makeMyValue(int i) {
    class MyIH implements MyValue {
      public int getInt() { return i; }
    }
    return new MyIH();
  }
//----(4)----
  MyValue makeMyValue(final int i) {
    class MyIH implements MyValue {
      public int getInt() { return i; }
    }
    return new MyIH();
  }
//----(5)----
   MyValue makeMyValue(int i) {
     return new MyIH(i);
   }
   static class MyIH implements MyValue {
     final int j;
     MyIH(int i) { j = i; }
     public int getInt() { return j; }
   }

Select the two correct answers.

  • (a) The method labeled (1).
  • (b) The method labeled (2).
  • (c) The method labeled (3).
  • (d) The method labeled (4).
  • (e) The method labeled (5).


(d) and (e)

Note

The methods labeled (1) and (3) will not compile, since the non-final parameter i is not accessible from within the inner class.

The syntax of the anonymous class in the method labeled (2) is not correct, as the parameter list is missing.




PreviousNext

Related