java 面向对象多态

1  多态性

  (1)方法的重载和重写

(2)对象的多态性

2  对象的多态性:

 (1)向上转型:  程序会自动完成

     父类  父类对象 =  子类实例

  (2)向下转型:强制类型转换

     子类 子类对象 = (子类) 父类实例

3  案例代码:

package csdn.zyl.demo;
class A12{
 public void tell1()
 {
  System.out.println("A12--tell1");
 }
 public void tell2()
 {
  System.out.println("A12--tell2");
 }
}
class B1 extends A12{
 public void tell1(){
  System.out.println("B1--tell1");
 }
 public void tell3(){
  System.out.println("B1--tell3");
 }
}
public class DuoTaiDemo {
 public static void main(String[] args) {
  // TODO Auto-generated method stub
      //向上转型
  System.out.println("向上转型结果");
  B1 b = new B1();
  A12 a = b;
  a.tell1(); //tell1 ()重写
  a.tell2();
  //向下 转型
  System.out.println("向下转型结果");
  A12 a1 = new B1();
  B1 b1 = (B1)a1;
  b1.tell1();
  b1.tell2();
  b1.tell3();
  
 }
}

案例结果:

向上转型结果
B1--tell1
A12--tell2
向下转型结果
B1--tell1
A12--tell2
B1--tell3

4  多态性的使用:

package csdn.zyl.demo;
// 多态的应用
class A111{
 public void  tell1(){
  System.out.println("A--tell1");
 }
}
class B111 extends A111{
 public void tell2(){
  System.out.println("B--tell2");
 }
}
class C111 extends A111{
 public void tell3()
 {
  System.out.println("S--tell3");
 }
}
class D111 extends A111
{
 
}
public class PolDemo {
 public static void main(String[] args) {
  // TODO Auto-generated method stub
      say(new B111());
      say(new C111());
      say(new D111());
 }
   public static void say(A111 a)
   {
     a.tell1();
   }
}


案例结果:

A--tell1
A--tell1
A--tell1


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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值