接口与内部类

  • 接口

接口中的方法自动地属于public类型。接口中不能含有实例域,也不能在接口中实现方法。提供实例域和方法的实现必须在实现接口的类中来完成。可以将接口看成抽象类。当然和抽象类还是有点区别的。

现在要在类中实现一个接口,通常要做以下步骤

1、将类声明为实现的接口

需要用到关键字implements

class Employee implements compareTo<Employee>

2、将接口中的所有方法定义

public int compareTo(Employee other)

即是实现接口中的方法

虽然接口的方法在声明时可以自动为public 而实现接口中的方法是必须声明public等访问权限。

/* 重写了compareTo函数 
* 薪金小于比较对象返回-1 
* 大于返回1 * 否则返回0 
*/ 
@Override public int compareTo(Employee1 other) 
{ 
if(salary<other.getSalary())return -1; 
if(salary>other.getSalary())return 1; 
return 0; 
} 
Arrays.sory(staff)//对staff排序,要求数组中的元素必须属于实现了comparable接口的类
  • 接口的特性
检查一个对象是否实现了某个接口
if(anObject instanceof Comparale){….};
 
  • 对象的克隆
对于每个类,都需要做出下列判断:
1、默认的clone方法是否满足要求
2、默认的clone方法能否通过调用可变子对象的clone得到修补
3、是否不应该使用clone
实际上,3是默认的。如果选择1或2,类必须:
1、实现cloneable接口。
2、使用public访问策略重新定义clone方法。
cloneable是java提供的标记接口,没有方法。
class Employee implements Cloneable
{
	//将权限设置成为public,改变返回类型
   public Employee clone() throws CloneNotSupportedException
  {
	return (Employee) super.clone();//调用super.clone()
   }
}
  • 接口和回调
public class TimerTest {
    public static void main(String [] args)
    {
        ActionListener listener=new TimePrinter();
        Timer t=new Timer(10000,listener);//定时器每隔10秒发出事件
         t.start();
        JOptionPane.showMessageDialog(null, "Quit program?");
        System.exit(0);
    }
}

class TimePrinter implements ActionListener
{
    /**
     * 监听定时器时间,每到了固定时间
     * 调用事件发送现在时间,并且响一声
     */
    @Override
    public void actionPerformed(ActionEvent event)
    {
        Date now=new Date();
        System.out.println("At the tone,the time is  "+now);
        Toolkit.getDefaultToolkit().beep();
    }
}
  • 内部类

为什么要使用内部类

1、可以访问类定义所在的数据,包括私有数据

2、可以对同一个包隐藏

3、定义一个回调函数,用匿名内部类比较方便

匿名内部类

假如仅仅创建这个类的一个对象,就可以不用命名了。

public void start(int interval,final boolean beep)
{
        ActionListener listener=new ActionListener()
    {
            public void actionPerformed(ActionEvent event)
        {
                .......
        }
        .......
    }
}
它的含义是:创建一个ActionListened接口的类的新对象,需要实现的方法ActionPerformed在{}里面实现
用于构造对象的任何参数都放在括号()后面。
语法形式为:
new SuperType(construction paramenters)
{
inner class methods and data;
}
 

posted on 2011-08-10 10:16  烟波钓徒  阅读(404)  评论(0编辑  收藏  举报