Java OCA OCP Practice Question 2345

Question

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*/
}
  • a new Printable();
  • b new Printable(){};
  • c new Printable() { public void print() {}};
  • d new Printable() public void print() {};
  • e new Printable(public void print() ) {}};
  • f new Printable() { void print() {}};
  • g None of the above


c

Note

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.




PreviousNext

Related