Dengke Liu
Dengke Liu

Reputation: 141

Test Killer 310-065 for SCJP (Java)

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?

Upvotes: 0

Views: 534

Answers (2)

blyons
blyons

Reputation: 33

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.

Upvotes: 0

user1373164
user1373164

Reputation: 448

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

Upvotes: 3

Related Questions