java匿名接口实现

https://blog.csdn.net/wo198711203217/article/details/80536584

java接口实现有两种方式: 
1、显式的实现(implements) 
伪代码:

interface InterfaceName
{
  //abstract methods declaration
}

class ClassName implements InterfaceName
{
    //abstract methods overwrite
}
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9

示例代码:

package com.lx;

interface Runner
{
    public void run();
}

class Person implements Runner
{

    @Override
    public void run() {
        // TODO Auto-generated method stub
        System.out.println("我是人类,我会跑。");
    }
}

public class DemoInterface
{
    public static void main(String[] args) {
        Runner r=new Person();

        r.run();
    }
}
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  • 24
  • 25

运行结果: 
我是人类,我会跑。 
2、隐式的实现 
伪代码:

interface InterfaceName
{
    //abstract methods declaration
}

InterfaceName i=new InterfaceName() {
    //abstract methods overwrite
}
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8

示例代码:

package com.lx;

interface Runner
{
    public void run();
}


public class DemoInterface
{
    public static void main(String[] args) {
        Runner r=new Runner() {

            @Override
            public void run() {
                // TODO Auto-generated method stub
                System.out.println("我是匿名的,但是我会跑。。。");
            }
        };
        r.run();
    }
}
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22

可以发现,方式2比方式1省了好多代码,至少不用先定义一个人类去实现Runner接口。 
如果有些场合,只需要临时需要创建一个接口的实现类,上面的”技巧”可以用来简化代码。

猜你喜欢

转载自blog.csdn.net/zhangdaohong/article/details/82633056