1、多態(tài)性的體現(xiàn):
????方法的重載和重寫
????對象的多態(tài)性
2、對象的多態(tài)性
????向上轉(zhuǎn)型:程序會自動完成
????????父類 父類對象 = 子類實例
????向下轉(zhuǎn)型:強制類型轉(zhuǎn)換
????????子類 子類對象 = (子類)父類實例
public class A {
public void tell1() {
System.out.println("A----tell1");
}
public void tell2() {
System.out.println("A----tell2");
}
}
public class B extends A {
public void tell1() {
System.out.println("B----tell1");
}
public void tell3() {
System.out.println("B----tell3");
}
}
public class Demo {
public static void main(String[] args) {
// 向上轉(zhuǎn)型
B b = new B();
A a = b;
a.tell1(); // 因為tell1方法被B類重寫了,所以調(diào)用的是重寫之后的方法
a.tell2();
// Output result:
// B----tell1
// A----tell2
// 向下轉(zhuǎn)型
A a = new B(); // 注意此處是 new B(),因為如果 new A() ,那么new出來的對象與B是沒有什么直接關(guān)系的,因此 進(jìn)行強轉(zhuǎn)時會報錯:不能轉(zhuǎn)換為B類型
B b = (B)a;
b.tell1();
b.tell2();
b.tell3();
// Output result:
// B----tell1
// A----tell2
// B----tell3
}
}
接口當(dāng)中只允許存在抽象方法
interface USB {
void start(); // 可以省略 public abstract
void stop();
}