开发者

Doubt related to interface instantiation in Java

开发者 https://www.devze.com 2022-12-18 16:12 出处:网络
The following program when run will product stackoverflow as output. I want to know what is happenin开发者_运维百科g in the line where a TestA is being instantiated.

The following program when run will product stackoverflow as output.

I want to know what is happenin开发者_运维百科g in the line where a TestA is being instantiated.

interface TestA { String toString(); }

class Test 
{
  public static void main(String[] args) 
  {
     // whats going on in this line ???
     System.out.println(new TestA() {public String toString() { return "stackoverflow"; } });
  }
}


You are instantiating an anonymous class, that implements the TestA interface.

This technique is very useful for e.g. event listeners in GUI programming, since it saves you from creating a bunch of named single-use classes.


What you are doing is to create an anonymus class that implements the interface. To make it a little clearer you can write this as well:

interface TestA { String toString(); }

class Test 
{
  public static void main(String[] args) 
  {
    TestA test = new TestA()
    {
        public String toString()
        {
            return "stackoverflow";
        }
    };

    System.out.println(test);
  }
}


Following class is created on the fly (without any name) :

class Annonymous implements TestA 
{ 
    String toString() {
        return "stackoverflow";
    } 
}
0

精彩评论

暂无评论...
验证码 换一张
取 消