一、java中的接口本質上是加約束的抽象類
//抽象類
public abstract class AExample
{
public abstract int add(int x,int y);
public abstract int sub(int x,int y);
}
//接口
public interface IExample
{
public int add(int x,int y);
public int sub(int x,int y);
}
通常的用法是創建一個新類,這個類實現接口或從抽象類派生。這個新類要實現接口中定義的全部方法,或實現抽象類中的全部抽象方法。
1、抽象類的實現方法:
public class MyClass extends AExample
{
//其它成員定義:略
//實現抽象類中的抽象方法
public int add(int x,int y)
{
return x+y;
}
public int sub(int x,int y)
{
return x-y;
}
//其它部分:略
}
使用方法:
AExample ae = new MyClass();
int s = ae.add(4,2);
int t = ae.sub(4,2);
2、接口的實現方法:
public class MyClass implements IExample
{
//其它成員定義:略
//實現抽象類中的抽象方法
public int add(int x,int y)
{
return x+y;
}
public int sub(int x,int y)
{
return x-y;
}
//其它部分:略
}
使用方法:
IExample ae = new MyClass();
int s = ae.add(4,2);
int t = ae.sub(4,2);
可見,兩者本質是一樣的,使用方法也是非常相似的。
二、特殊實現方法
這里不使用上述從抽象類的派生新類和用接口實現的新類的方法。
1、先來看一下數組的初始化例子:
int[] array;
這樣定義數組后,array僅僅是個引用,array[0],array[1]沒有實現,即不存在。但是如果在定義時初始化為:
int[] array = new int[]{1,2};
1和2看成是數組的兩個“成員實例”。這時array[0],array[1]就被實現了,也即array被實現了。
2、接口和抽象類都可以用類似的方法實現:
- AExample ae = new AExample(){
- public int add(int x,int y)
- {
- return x+y;
- }
- public int sub(int x,int y)
- {
- return x-y;
- }
- };
- int s = ae.add(4,2);
- int t = ae.sub(4,2);
這里的所謂“成員實例”就是具體的兩個方法add和sub的實現。
又
- IExample ae = new IExample(){
- public int add(int x,int y)
- {
- return x+y;
- }
- public int sub(int x,int y)
- {
- return x-y;
- }
- };
- int s = ae.add(4,2);
- int t = ae.sub(4,2);
很神奇吧!
三、總結
實際上這種方法在一般情況下用得比較少,主要應用于事件處理問題當中。并且主要使用接口。
上面的形式是本人在學習java的事件處理編程時遇到一個疑問:為什么java的事件監聽者注冊時使用的形式是這樣的:
//Person是本人設計的一個含有事件處理的類,PersonListener是個接口--監聽者接口
Person p = new Person("Tong",53);
/////////////////////////////////////////////////////////////////////////////////////////////////////////
//創建事件監聽者接口的實例并注冊
p.addPersonListener( new PersonListener(){
public void OnNameChanged(PersonEventObject e)
{
//自定義事件處理代碼
System.out.println("Name :"+((Person)(e.getSource())).getName());
}
public void OnAgeChanged(PersonEventObject e)
{
//自定義事件處理代碼
System.out.println("Name :"+((Person)(e.getSource())).getName());
}
});
//////////////////////////////////////////////////////////////////////////////////////////////////
將上述p.addPersonListener(...)分成兩個步驟就一清二楚了:
PersonListener pl = new PersonListener(){
public void OnNameChanged(PersonEventObject e)
{
//自定義事件處理代碼
System.out.println("Name :"+((Person)(e.getSource())).getName());
}
public void OnAgeChanged(PersonEventObject e)
{
//自定義事件處理代碼
System.out.println("Name :"+((Person)(e.getSource())).getName());
}
};
p.addPersonListener(pl);
看一看,就是我們上面討論的問題。
通過這個例子,希望許多初學java的人會有所得。
原文參考自站長網http://www.software8.co/wzjs/java/2743.html