Java OCA OCP Practice Question 38

Question

Which of the following statements are true? (Choose all that apply.)

  • A. Given that Inner is a nonstatic class declared inside a public class Outer and that appropriate constructor forms are defined, an instance of Inner can be constructed like this:
new Outer().new Inner() 
  • B. If an anonymous inner class inside the class Outer is defined to implement the interface ActionListener, it can be constructed like this:
new Outer().new ActionListener() 
  • C. Given that Inner is a nonstatic class declared inside a public class Outer and that appropriate constructor forms are defined, an instance of Inner can be constructed in a static method like this:
new Inner() 
  • D. An anonymous class instance that implements the interface MyInterface can be constructed and returned from a method like this:
1. return new MyInterface(int x) { 
2.   int x; 
3.   public MyInterface(int x) { 
4.     this.x = x;
5.   }
6. }; 


A.

Note

Construction of a named and nonstatic inner class requires an instance of the enclosing class.

Often this enclosing instance is provided via the implied this reference, but an explicit reference can be used in front of the new operator.

Anonymous inner classes can be instantiated only at the same point they are declared, so B is illegal.

C is illegal because Inner is a nonstatic inner class, and so it requires a reference to an enclosing instance when it is constructed.

D is illegal because it is trying to use arguments to the constructor of an anonymous inner class that implements an interface.




PreviousNext

Related