Return to site

JAVA CERTIFICATION QUESTION: Anonymous inner class instantiation

· java

Given:

public class OcpW47 {
    class Foo {
        void m() {
            System.out.println("Foo");
        }
    }

    public static void main(String[] args) {
        Foo foo = new OcpW47().new Foo() { //line n1
            void m() {
                System.out.println("Bar");
            }
        };
        foo.m();
    }

}

Which statement is correct, choose one.

* It compiles and prints nothing

* It compiles and prints 'Foo'

* It compiles and prints 'Bar'

* It compiles with 'Foo foo = OcpW47.new Foo(){' at line n1

* It compile with 'Foo foo = new OcpW47.Foo(){' at line n1

#java #certificationquestion #ocp

Answer:

It compiles and prints 'Bar'

Foo is an inner class, not a static nested one.

So the syntax of the declaration is valid.

The instantiation used an anonynous class that redefines the behavior of the 'm()' method.

So it prints 'Bar'.