java 匿名内部类

来源:互联网 发布:ubuntu 未找到deb命令 编辑:程序博客网 时间:2024/05/24 05:18


/**
 *
 */
package com.card;

/**
 * 匿名内部类
 *
 * by Zhiwang Zhang on 2014年7月18日
 */
public class Test100 {
 public static void main(String[] args) {
  Test100 test = new Test100();
  // 接口不能被实例化
  // Plant p = new Plant();
  test.func(new Plant() {
   // 这个匿名内部类相当于接口Plant的实现类,在实现类里面实现了父类的所有方法
   @Override
   public void plant() {
    System.out.println("I'll plant a tree.");
   }

   public void tree() {
    // TODO Auto-generated method stub
    System.out.println("Hello world!");
   }

   @Override
   public void water() {
    // TODO Auto-generated method stub
    System.out.println("I'm watering a flower.");
   }
  });
 }

 public void func(Plant plant) {
  plant.water();
  plant.plant();
 }
}

interface Plant {
 void plant();

 void water();
}

0 0
原创粉丝点击