Given the following code, which option, when inserted at /*INSERT CODE HERE*/, will instantiate an anonymous class referred to by the variable printable?
interface Printable { void print(); } class Main { Printable printable = /*INSERT CODE HERE*/ }
Printable()
;Printable()
{};Printable()
{ public void print()
{}};Printable()
public void print()
{};print()
) {}};Printable()
{ void print()
{}};c
To instantiate an anonymous class that can be referred to by the variable printable of type Printable, the anonymous class must implement the interface, implementing all its methods.
Because interface Printable defines method print()
(methods defined in an interface are implicitly public and abstract), it must be implemented by the anonymous class.
Only option (c) correctly implements method print()
.
Following is its correctly indented code, which should be more clear:.
new Printable() { public void print() { } };
Option (b) doesn't implement print()
.
Option (a) tries to instantiate the inter- face Printable, which isn't allowed.
Option (f) looks okay, but isn't because it makes the method print()
more restrictive by not defining it as public.