多态性

从其他地方看的一些解释,总结一下:

class A ...{  
         public String show(D obj)...{  
                return ("A and D");  
         }   
         public String show(A obj)...{  
                return ("A and A");  
         }   
}   
class B extends A...{  
         public String show(B obj)...{  
                return ("B and B");  
         }  
         public String show(A obj)...{  
                return ("B and A");  
         }   
}  
class C extends B...{}   
class D extends B...{}  
    A a1 = new A();  
    A a2 = new B();  
    B b = new B();  
    C c = new C();   
    D d = new D();   
    System.out.println(a1.show(b));   ① A and A 
    System.out.println(a1.show(c));   ② A and A
    System.out.println(a1.show(d));   ③ A and D 
    System.out.println(a2.show(b));   ④ B and A 
    System.out.println(a2.show(c));   ⑤ B and A 
    System.out.println(a2.show(d));   ⑥ A and D 
    System.out.println(b.show(b));    ⑦ B and B 
    System.out.println(b.show(c));    ⑧ B and B 
    System.out.println(b.show(d));    ⑨ A and D 

方法的重写Overriding和重载Overloading是Java多态性的不同表现。
此处只谈重写。

首先,子类重写父类的方法后,子类调用父类的同名方法调用的就是重写过的方法。
当超类对象引用变量引用子类对象时,被引用对象的类型而不是引用变量的类型决定了调用谁的成员方法,但是这个被调用的方法必须是在超类中定义过的,也就是说被子类覆盖的方法。 (但是如果强制把超类转换成子类的话,就可以调用子类中新添加而超类没有的方法了。)通俗而言,宠物有叫的办法,狗继承了宠物的方法,重写了叫的方法。那么,用宠物的引用指向狗是对的,因为狗是宠物,但这个宠物究竟还是狗,叫的时候还是汪汪叫。
优先级由高到低依次为:this.show(O)、super.show(O)、this.show((super)O)、super.show((super)O)。
意思是在当前对象的类中有方法则调用,没有就向上找,父类也没有就将对象向父类靠近
a1.show(b),b是B,也是A,首先a1是A。A只有showD和showA,所以A调用showB时会将B向A靠,即ShowA。2、 3同理。
a2.show(b),A是宠物,但A是狗,所以A会调用狗重写了宠物的方法,A只有showD和showA,b是B,也是A,所以是a2.showA,调用狗重写的方法。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值