1.編寫接口程序RunTest.java,通過接口回調實現多態性。解釋【代碼4】和【代碼6】的執行結果為何不同?
interface Runable{
void run();
}
class Cat implements Runable{
public void run(){
System.out.println("貓急上樹..");
}
}
【代碼1】 ?// 參照Cat類,定義Dog類并實現Runable接口
public void run(){
System.out.println("狗急跳墻..");
}
}
public class RunTest{
public static void main(String[] args){
【代碼2】 ?// 聲明Runable接口變量r
【代碼3】 ?// 接口變量r中存放一個Cat對象的引用
????????【代碼4】 ?// 調用Cat對象的run()方法
System.out.println("-----------");
【代碼5】 ?// 接口變量r中存放一個Dog對象的引用
????????【代碼6】 ?// 調用Dog對象的run()方法
}
}
// 定義接口
interface Runable {void run(); // 抽象方法
}// 定義Cat類并實現Runable接口
class Cat implements Runable {@Overridepublic void run() {System.out.println("貓急上樹..");}
}// 定義Dog類并實現Runable接口
class Dog implements Runable {@Overridepublic void run() {System.out.println("狗急跳墻..");}
}// 測試類
public class RunTest {public static void main(String[] args) {// 【代碼2】聲明Runable接口變量rRunable r;// 【代碼3】接口變量r中存放一個Cat對象的引用r = new Cat();// 【代碼4】調用Cat對象的run()方法r.run();System.out.println("-----------");// 【代碼5】接口變量r中存放一個Dog對象的引用r = new Dog();// 【代碼6】調用Dog對象的run()方法r.run();}
}