一婶恼、多態(tài)性
- 多態(tài)性的體現(xiàn):
- 方法的重載和重寫
- 對(duì)象的多態(tài)性
- 對(duì)象的多態(tài)性:
- 向上轉(zhuǎn)型:程序會(huì)自動(dòng)完成
父類 父類對(duì)象 = 子類實(shí)例 - 向下轉(zhuǎn)型:強(qiáng)制類型轉(zhuǎn)換
子類 子類對(duì)象 = (子類)父類實(shí)例
代碼一 : 向上轉(zhuǎn)型
class A2{
public void tell1() {
System.out.println("A2---tell1");
}
public void tell2() {
System.out.println("A2---tell2");
}
}
class B2 extends A2{
public void tell1() {
System.out.println("B2---tell1");
}
public void tell3() {
System.out.println("B2--tell3");
}
}
public class Demo22 {
public static void main(String[] args) {
//向上轉(zhuǎn)型
B2 b = new B2();
A2 a=b;
a.tell1();//tell1是重寫的,調(diào)用的是重寫之后的方法
a.tell2();
}
}
結(jié)果:
B2---tell1
A2---tell2
代碼二 : 向下轉(zhuǎn)型
class A2{
public void tell1() {
System.out.println("A2---tell1");
}
public void tell2() {
System.out.println("A2---tell2");
}
}
class B2 extends A2{
public void tell1() {
System.out.println("B2---tell1");
}
public void tell3() {
System.out.println("B2--tell3");
}
}
public class Demo22 {
public static void main(String[] args) {
//向下轉(zhuǎn)型
A2 a2 = new B2();
B2 b2 = (B2)a2;
b2.tell1();
b2.tell2();
b2.tell3();
}
}
結(jié)果:
B2---tell1
A2---tell2
B2--tell3
代碼三 : 類型轉(zhuǎn)換失敗
class A2{
public void tell1() {
System.out.println("A2---tell1");
}
public void tell2() {
System.out.println("A2---tell2");
}
}
class B2 extends A2{
public void tell1() {
System.out.println("B2---tell1");
}
public void tell3() {
System.out.println("B2--tell3");
}
}
public class Demo22 {
public static void main(String[] args) {
//向下轉(zhuǎn)型
A2 a2 = new A2(); //將B2改成A2德迹,報(bào)錯(cuò) - 類型轉(zhuǎn)換失敗
B2 b2 = (B2)a2;
b2.tell1();
b2.tell2();
b2.tell3();
}
}
結(jié)果:
Exception in thread "main" java.lang.ClassCastException: cn.sec.ch02.A2 cannot be cast to cn.sec.ch02.B2
at cn.sec.ch02.Demo22.main(Demo22.java:35)
二、多態(tài)性應(yīng)用
代碼
class A3{
public void tell1(){
System.out.println("A3---tell1");
}
}
class B3 extends A3{
public void tell2(){
System.out.println("B3--tell2");
}
}
class C3 extends A3{
public void tell3() {
System.out.println("C3--tell3");
}
}
class D3 extends A3{
}
public class Demo23 {
public static void main(String[] args) {
// TODO Auto-generated method stub
say(new B3());
say(new C3());
say(new D3());
}
/**
* 此方法無論傳B3還是C3都要調(diào)用到tell1的執(zhí)行
*/
public static void say(A3 a) {
a.tell1();
}
}
結(jié)果:
A3---tell1
A3---tell1
A3---tell1
三橙喘、instanceof關(guān)鍵字
在Java中可以使用
instanceof
關(guān)鍵字判斷一個(gè)對(duì)象到底是不是一個(gè)類的實(shí)例陆爽。
代碼
class A4{
public void tell1() {
System.out.println("A4---tell1");
}
public void tell2() {
System.out.println("A4---tell2");
}
}
class B4 extends A4{
public void tell1() {
System.out.println("B4---tell1");
}
public void tell3() {
System.out.println("B4--tell3");
}
}
public class Demo24 {
public static void main(String[] args) {
A4 a4 = new A4();
System.out.println(a4 instanceof A4);
System.out.println(a4 instanceof B4);
A4 a = new B4(); //向上轉(zhuǎn)型
System.out.println(a instanceof A4);
System.out.println(a instanceof B4);
}
}
結(jié)果:
true
false
true
true