zoukankan      html  css  js  c++  java
  • java上转型和下转型(对象的多态性)

    /*上转型和下转型(对象的多态性)
    *上转型:是子类对象由父类引用,格式:parent p=new son
    *也就是说,想要上转型的前提必须是有继承关系的两个类。
    *在调用方法的时候,上转型对象只能调用父类中有的方法,如果调用子类的方法则会报错
    *下转型:是父类向下强制转换到子类对象
    *前提是该父类对象必须是经过上转型的对象。
    *
    *代码示例:*/

     1 abstract class Parent{
     2     abstract void grow();
     3 }
     4 class Son extends Parent{
     5     void grow(){
     6         System.out.println("我比父亲成长条件好");
     7     }
     8     void dance(){
     9         System.out.println("我会踢球");
    10     }
    11 }
    12 public class test {
    13     public static void main(String[] args) {
    14         //上转型,用父类的引用子类的对象
    15         Parent p=new Son();
    16         //调用父类中有的方法
    17         p.grow();
    18         //p.dance();这里会报错,因为父类中没有dance()方法
    19         
    20         //对进行过上转型的对象,进行强制下转型
    21         Son s=(Son)p;
    22         //调用子类中的方法
    23         s.dance();
    24     }
    25 }

    /*
    * 在我们写程序中,很少会把代码写死,比如说还会有daughter类
    * 然后在封装函数来调用对象,说不定会用到子类的方法,这里我们来讲解一下这一方面的知识*/

     1 abstract class Parent{
     2     abstract void grow();
     3 }
     4 class Son extends Parent{
     5     void grow(){
     6         System.out.println("我比父亲成长条件好一点:son");
     7     }
     8     void play(){
     9         System.out.println("我会踢球");
    10     }
    11 }
    12 class Daughter extends Parent{
    13     void grow(){
    14         System.out.println("我比父亲成长条件好很多:daughter");
    15     }
    16     void dance(){
    17         System.out.println("我会跳舞");
    18     }
    19 }
    20 public class test {
    21     public static void main(String[] args) {
    22         Parent p=new Son();
    23         show(p);
    24         Parent p2=new Daughter();
    25         show(p2);
    26     }
    27     public static void show(Parent p){
    28             //现将父类中有的方法输出
    29             p.grow();
    30             //对进行过上转型的对象进行类型判断,然后进行相应的强制下转型
    31             if(p instanceof Son){
    32                 //判断是哪个类的上转型对象,然后进行下转型
    33                 Son s=(Son)p;
    34                 //调用子类中的方法
    35                 s.play();
    36             }else if(p instanceof Daughter){
    37                 Daughter d=(Daughter)p;
    38                 d.dance();
    39             }
    40             
    41     }
    42 }

    /*
    * 在上转型中,编译程序的时候,看父类中有没有对象调用的方法,没有的话,就报错
    * 例如:Parent p=new Son();
    * p.play();
    * play()方法在父类中没有,所以会报错
    * 在运行的时候,看子类中是否有调用的方法,有的话,运行子类的方法(重写父类的方法)
    *
    * */

  • 相关阅读:
    git fetch pull checkout区别
    git config配置文件
    php错误以及常用笔记
    Linux chmod命令修改文件与文件夹权限的命令附实例
    学习笔记 2016-04-12
    MYSQL 【汇总数据】 【分组数据】 学习记录
    Mysql常用函数
    学习笔记
    a++ ++a 文件上传函数错误 smarty模板特点
    算法稳定性相关
  • 原文地址:https://www.cnblogs.com/zxxiaoxia/p/4178049.html
Copyright © 2011-2022 走看看