Saturday, August 7, 2010

Anonymous Inner Classes:

Courtesy of SCJP Sun® Certified Programmer for Java™ 6 Study Guide Exam (310-065) (9780071591065)
Chapter 8, Exercise 2


Which create an anonymous inner class from within class Bar? (Choose all that apply.)

  1. Boo f = new Boo(24) { };

    Incorrect because it passes int to Boo constructor, and no such constructor is defined in the Boo class

  2. Boo f = new Bar() { };

    Correct because anonymous inner classes are no different from any other class when it comes to polymorphism. That means you are always allowed to declare a reference variable of the superclass type and have that reference variable refer to an instance of a subclass type, which in this case is an anonymous subclass of Bar. Since Bar is a subclass of Boo, it all works. 

  3. Boo f = new Boo() {String s; };

    Same as Option B. This is the correct syntax for creating an instance of Boo

  4. Bar f = new Boo(String s) { };

    Incorrect because it violates the rules of polymorphism; you cannot refer to a superclass type using a reference variable declared as the subclass type. The superclass doesn’t have everything the subclass has.

  5. Boo f = new Boo.Bar(String s) { };
          Incorrect syntax.    

No comments:

Post a Comment