java匿名接口的實現


顯式的實現(implements)

interface InterfaceName
{
  //abstract methods declaration
}

class ClassName implements InterfaceName
{
  //abstract methods overwrite
}

示例代碼:

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

2、隱式的實現

interface InterfaceName
{
  //abstract methods declaration
}

InterfaceName i=new InterfaceName() {
  //abstract methods overwrite
}

示例代碼:

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


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM