Test Killer 310-065 for SCJP (Java)

502 Views Asked by At

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?

2

There are 2 best solutions below

0
user1373164 On

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";}
     });
  }
}
0
blyons On

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.