Java-多态

概述

理解:同一个事件发生在不同的对象上会有不同的结果

Java中的多态定义

多态指允许不同类的对象对同一消息做出响应。即同一消息可以根据发送对象的不同而采用多种不同的行为方式。多态性就是对象多种表现形式的体现。

多态存在的三个必要条件

  1. 继承
  2. 重写
  3. 父类引用指向子类对象

优点

可替换性、可扩充性、简洁性、灵活性、接口性

多态的类型转换

向上转型

限制对持有功能的访问

向下转型

使用子类中的特有方法

instanceof

判断对象的具体类型

示例:

package text;

import text.entity.Cat;
import text.entity.Dog;

/**
 * @ClassName : PolymorphicDemo
 * @Description : PolymorphicDemo
 * @Author : mt
 * @Date: 2023-08-04 18:02
 */
public class PolymorphicDemo {
    public static void main(String[] args) {
        //调用
        Cat c = new Cat();
        method(c);
        method(new Dog()); //Dat d = new Dat()
    }
    public static void method(Cat c){
        c.eat();
    }
    public static void method(Dog d){
        d.eat();
    }
}
package text.entity;

/**
 * @ClassName : Animal02
 * @Description : Animal02
 * @Author : mt
 * @Date: 2023-08-04 17:50
 */
public abstract class Animal02 {
    abstract void eat();
}
package text.entity;

/**
 * @ClassName : Cat
 * @Description : Cat
 * @Author : mt
 * @Date: 2023-08-04 17:48
 */
public class Cat extends Animal02{
        public void eat(){
            System.out.println("吃鱼");
        }
        public void catchmouse(){
            System.out.println("抓老鼠");
        }

}
package text.entity;

import org.omg.Messaging.SyncScopeHelper;

/**
 * @ClassName : Dog
 * @Description : Dog
 * @Author : mt
 * @Date: 2023-08-04 17:49
 */
public class Dog extends Animal02{
    public void eat(){
        System.out.println("啃骨头");
    }
    public void lookhome(){
        System.out.println("看家");
    }
}

示例:父类的引用指向子类

package text;

import text.entity.Animal02;
import text.entity.Cat;
import text.entity.Dog;

/**
 * @ClassName : PolymorphicDemo
 * @Description : PolymorphicDemo
 * @Author : mt
 * @Date: 2023-08-04 18:02
 */
public class PolymorphicDemo {
    public static void main(String[] args) {
        //调用
//        Cat c = new Cat();
//        method(c);
//        method(new Dog()); //Dat d = new Dat()
        //父类的引用指向子类
        Animal02 c = new Cat();
        method(c);
        method(new Dog());
    }
    public static void method(Animal02 a){
        a.eat();
    }
    public static Animal02 gaet() {
        return new Dog();
    }
}

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值