標籤:
/**
* @author Administrator
*
* @description 介面測試類別
* @history
*/
interface Interface{
public static final String INFO = "helloeclipse";
public void print(); // 定義方法
public abstract void printInfo();
}
class I implements Interface{
public void print() {
// 方法實現
System.out.println(INFO); // helloeclipse
}
public void printInfo() {
// ...
}
}
public class InterfaceTestDemo {
/***@description
*@param args
*/
public static void main(String[] args) {
// 介面interface
// 介面interface和抽象類別abstract一樣不能直接執行個體化必須通過子類來實現
new Interface(){
public void print() {
// 匿名內部類,方法實現
System.out.println(INFO); // helloeclipse
}
public void printInfo() {
// ...
}
};
// 介面和抽象類別對比,介面更像一種規範、抽象類別更像一種模板
// 抽象類別定義一些公用的實現,以及一些未實現的方法交給子類具體實現特定的功能-模板方法
}
}
/**
* @author Administrator
*
* @description 抽象類別學習測試類別
* @history
*/
abstract class Abstract{ // 定義抽象類別
public final static String INFO = "helloeclipse"; // 定義全域變數/常量
abstract public void print(); // 定義抽象方法
// 抽象類別不能直接執行個體化,抽象類別的子類如果不是抽象類別那麼一定要實現所有的抽象方法
}
class AbstractZiLei extends Abstract{ // 定義抽象子類
public void print() { // 實現子類方法
System.out.println(INFO);
}
}
public class AbstractTestDemo {
/**
*@description
*@param args
*/
public static void main(String[] args) {
// 介面和抽象類別interface,abstract
// 抽象類別:含有抽象方法的類叫做抽象類別用abstract修飾的
new Abstract(){public void print() {
System.out.println(INFO); // 匿名抽象類別實現
}
};
// 抽象類別能不能被final修飾呢?final定義的類為終結類,抽象類別是需要子類來實現的
// final abstract class Abstract{ //... } // 編譯報錯
}
}
黑馬程式員-------介面和抽象類別