• Java面向对象--多态


    多态

    笔记要点


    多态:同一个对象拥有多种形态
    
    作用:把不同的数据类型进行统一,让程序有超强的扩展性
    
    
    小知识点:
    
    1. 把子类的对象赋值给父类的变量 --> 向上转型
       
       缺点:屏蔽掉子类中特有的方法
       
    2. 把父类的变量转化回子类的变量 --> 向下转型
    
       向下转型有可能有风险,java要求必须要写强制类型转换
       
       语法:(转换之后的数据类型)变量
    

    实践代码


    Client类
    public class Client {
      public static void main(String[] args) {
    //        Cat c = new Cat();
    //        Dog d = new Dog();
    //
    //        Person p = new Person();
    //        p.feedCat(c);
    //        p.feedDog(d);
          Cat c = new Cat(); // 创建一只猫
          // 可以把猫当作动物来看,把子类的对象赋值给对象的引用(变量)向上转型
          // 向上转型会屏蔽掉子类中特有的方法
          Animal cat = new Cat();
          Animal dog = new Dog();
          Animal elephant = new Elephant();
    
          // 向下转型前,站在动物的角度是不能抓老鼠的
          //cat.catchMouse();
    //      Person person = new Person();
    //      person.feed(cat);
    //      person.feed(dog);
    //      person.feed(elephant);
    
          // 多态: 把不同的数据类型进行统一
    
          // 向下转型
          Cat cc = (Cat) cat;
          cc.catchMouse(); // 猫又可以抓老鼠了
    
        }
    }
    
    
    Animal类
    public class Animal {
        public void eat() {
            System.out.println("猫吃鱼");
        }
    }
    
    
    Person类
    public class Person {
        public void feed(Animal animal) { //接受到的所有动物都是animal
            animal.eat();
        }
    //    public void feedCat(Cat c) {
    //        c.eat();
    //    }
    //    public void feedDog(Dog d) {
    //        d.eat();
    //    }
    //    public void feedElephant(Elephant e) {
    //        e.eat();
    //    }
    }
    
    
    Cat类
    // 猫是一种动物 --> 继承关系
    public class Cat extends Animal{
        public void eat() {
            System.out.println("猫吃鱼");
        }
        public void catchMouse() {
            System.out.println("猫喜欢抓老鼠");
        }
    }
    
    
    Dog类
    public class Dog  extends Animal{
        public void eat() {
            System.out.println("狗吃骨头");
        }
    }
    
    
    Elephant类
    public class Elephant extends Animal{
        public void eat() {
            System.out.println("大象吃香蕉");
        }
    }
    
    
  • 相关阅读:
    最新版-Python和Java实现Aes相互加解密
    tasker 实现短信监听和转发 解决短信验证码登录问题
    某宁 价格爬取 python
    python 获取 某东商品评论数
    xpath 使用
    frida hook 重载函数的几种写法
    Python 爬虫遇到形如 小说 的编码如何转换为中文?
    python 使用 pymysql 存,改dic类型数据
    Excel甘特图制作
    关于sunlike ERP的问题解决集
  • 原文地址:https://www.cnblogs.com/isChenJY/p/12780748.html
Copyright © 2020-2023  润新知