Can we create an object of an interface?

Viewed 45642
interface TestA {
    String toString();
}

public class Test {
    public static void main(String[] args) {
        System.out.println(new TestA() {
            public String toString() {
                return "test";
            }
        });
    }
}

What is the result?

A. test
B. null
C. An exception is thrown at runtime.
D. Compilation fails because of an error in line 1.
E. Compilation fails because of an error in line 4.
F. Compilation fails because of an error in line 5.

What is the answer of this question and why? I have one more query regarding this question. In line 4 we are creating an object of A. Is it possible to create an object of an interface?

6 Answers

The trick is not only about the anonymous inner class, this prints test cause it overrides the toString method and while System.out.println a Object it implicit call it's toString method.

Try this too... The name of anonymous class is generated!

Inter instance = new Inter() {
    public String getString() {
        return "HI" + this.getClass();
    }
};

We can create an object of an anonymous class, that implements the interface:

Anonymous classes enable you to make your code more concise. They enable you to declare and instantiate a class at the same time. They are like local classes except that they do not have a name. Use them if you need to use a local class only once.

If you have an interface, that declares one method toString, you can first create a class, that implements this inerface, and then create an object of this class:

interface TestA {
    String toString();
}

class TestB implements TestA {
    @Override
    public String toString() {
        return "test";
    }
}

public class Test {
    public static void main(String[] args) {
        System.out.println(new TestB());
    }
}

Or you can create an object of an anonymous class to simplify this code:

interface TestA {
    String toString();
}

public class Test {
    public static void main(String[] args) {
        System.out.println(new TestA() {
            @Override
            public String toString() {
                return "test";
            }
        });
    }
}

In both cases it prints "test".

Related