java隨筆之介面,java隨筆
/*
* 介面大致上可以分為:啞介面,抽象介面,介面類
* 啞介面:就是public,protected(注意protect有包許可權,只有本包才開放介面)方法
* 抽象介面:就是啞介面變為抽象方法,在前面追加abstract方法
* 介面類:就是interface 聲明的類(其本質上還是個類,可繼承,可向上轉換)
* interface
* 介面類本身又分為抽象類別,非抽象類別
* 非抽象類別:
* 裡面所有的方法都是public(不能用protect修飾) 但是介面本身具有包存取權限
* 裡面的域都是final和static的,意味著不能繼承,不能重載,只有一份記憶體
* interface可以向上轉換,這直接產生多態,對訊息迴圈很方便
* 抽象類別:在介面類前面加上abstarct 修飾即可
* 唯一的區別是抽象介面類不能有域的存在
* */
public class MyInterface {
public static void main(String []args){
Man man=new Man();
man.run();
//簡單的代理適配器模式
Delegate de=new Delegate();
de.run(new Adapter(man));
}
}
abstract interface action{
void run();
}
abstract class Human{
abstract void shape();//抽象方法 必須聲明抽象類別
Human(){
System.out.println("Human()");
}
}
class Man extends Human implements action{
void shape() {
// TODO Auto-generated method stub
System.out.println("man.shape()");
}
Man(){
System.out.println("man()");
shape();
}
public void run() {
// TODO Auto-generated method stub
System.out.println("man.run()");
}
}
class Man2 extends Human implements action{
void shape() {
// TODO Auto-generated method stub
System.out.println("man2.shape()");
}
Man2(){
System.out.println("man2()");
shape();
}
void sex(){//添加一個性別方法
}
public void run() {
// TODO Auto-generated method stub
System.out.println("man2.run()");
}
}
class Delegate{//代理action動作
void run(action act){
act.run();
}
Delegate(){
}
}
class Adapter implements action{//將對象適配成action
action act;
Adapter(Object obj){
act=(action) obj; //充分利用介面的向上轉換多態特性
}
public void run() {
// TODO Auto-generated method stub
act.run();
}
}