0

Given:

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

In the book, the result of this code is test.But I think TestA is an interface and you can't create an instance for TestA. Can anyone explain this to me?

Dengke Liu
  • 131
  • 1
  • 1
  • 10
  • `I think TestA is an interface and you can't create an instance for TestA`. Correct. Seems to be a typo in the book and should probably read `new Test()` – Eric J. Sep 30 '15 at 17:09

2 Answers2

3

new TestA() ... it's an anonymous class but there's typos around the parenthesis, should read like this:

interface TestA {String toString();}
public class Test{
  public static void main(String[] args){
     System.out.println(new TestA(){
        public String toString() {return "test";}
     });
  }
}
user1373164
  • 428
  • 4
  • 14
0

What this question is really getting at is whether or not you can create an anonymous inner class that implements an interface in another class. That is precisely what is happening in the original code above. Inside of the System.out.println() in the Test classes main method an anonymous inner class is created that implements the toString() method defined in the TestA interface. The implementation of the method returns the word "test" as a String. Have a look at

https://docs.oracle.com/javase/tutorial/java/javaOO/anonymousclasses.html

for further clarification.

blyons
  • 33
  • 10