zoukankan      html  css  js  c++  java
  • java polymorphism 多态

    运行时多态存在的三个必要条件:
    1.要有继承
    2.要有重写
    3.父类引用指向子类对象

    public class InstanceOfTest {
        public static void main(String[] args) {
            Cat c = new Cat("黑猫警长","黑色");
            Dog d = new Dog("大黄","黄色");
            
            //System.out.println(c instanceof Cat);//result:true
            //System.out.println(d instanceof Dog);//result:true
            
            //System.out.println(c instanceof Animal);//result:true
            //System.out.println(d instanceof Animal);//result:true
            
            //System.out.println(c instanceof Dog);错误:不兼容的类型Cat无法转换为Dog
            
            //System.out.println(c.name);//result:黑猫警长
            //System.out.println(d.name);//大黄
            
            InstanceOfTest t1 = new InstanceOfTest();
            t1.info(c);
            t1.getScream(c);//猫叫
        }
        
        
        public void info(Animal a) {
                System.out.println(a.name);
                //System.out.println(a.catColor);//result:找不到符号 变量catColor    类型为Animal的变量a
                if (a instanceof Cat) {
                    Cat c1 = (Cat)a;
                    System.out.println(c1.catColor);    //result:黑色
                }
        }    
            
        public void getScream(Animal a) {
            a.scream();    
        }    
    }
    
    class Animal {
        String name;
        
        Animal(String name) {
            this.name = name;    
        }
        
        public void scream() {
            System.out.println("动物叫");    
        }
    }
    
    class Cat extends Animal {
        String catColor;
        
        Cat(String name,String catColor) {//错误:需要标识符
            super (name);
            this.catColor = catColor;    
        }    
        
        public void scream() {
            System.out.println("猫叫");    
        }
    }
    
    class Dog extends Animal {
        String     dogColor;
        
        Dog(String name,String dogColor) {//错误:需要标识符
            super (name);
            this.dogColor = dogColor;    
        }
        
        public void scream() {
            System.out.println("狗叫");    
        }
    }
    
    /*
    1.子类中要使用父类的super构造方法,必须要在父类中先设定好构造方法。
    2.要直接使用子类的成员变量,则必须转换成子类的对象。父类引用指向子类对象只能访问其父类的成员变量。
    3.多态是由方法来实现的,要直接使用子类的方法无需转换成子类的对象,方法是和实际所传的对象绑定的。
    */
    
    
    /*
    运行时多态存在的三个必要条件:
            1.要有继承
            2.要有重写
            3.父类引用指向子类对象
    */
  • 相关阅读:
    java web 开发 IDE 下载地址
    【转】简述TCP的三次握手过程
    【转】TCP、UDP数据包大小的限制
    复习笔记2018.8.3
    .NET和UNITY版本问题
    LUA全总结
    C++全总结
    C# 全总结
    #region 常量和静态变量静态类readonly
    //todo 的用处
  • 原文地址:https://www.cnblogs.com/yhwsy/p/5705887.html
Copyright © 2011-2022 走看看