Java中多态、重写方法、instanceof运算符、重写equals的相关案例

本文通过实例详细介绍了Java中的多态性、方法重写、instanceof运算符以及equals方法的重写。通过电子宠物系统、学员比较和宠物喂食等场景,展示了如何在实际编程中应用这些概念。重写方法优化了系统功能,多态实现了不同类型的宠物喂食逻辑,instanceof则用于判断对象类型,以调用特定方法。
摘要由CSDN通过智能技术生成

一、代码及效果图

1.重写

案例:使用方法重写优化电子宠物系统

代码如下(示例):

package test1;

public class Dog extends Pet{
   
    private String type;

    public Dog(String name, int health, int cute, String type) {
   
        super(name, health, cute);
        this.type = type;
    }

    @Override
    public void show() {
   
        super.show();
        System.out.println("我是一只:"+type);
    }

    public String getType() {
   
        return type;
    }

    public void setType(String type) {
   
        this.type = type;
    }
}

package test1;

public class Penguin extends Pet{
   
    private String sex;

    public Penguin(String name, int health, int cute, String sex) {
   
        super(name, health, cute);
        this.sex = sex;
    }

    @Override
    public void show() {
   
        super.show();
        System.out.println("我的性别是:"+sex);
    }

    public String getSex() {
   
        return sex;
    }

    public void setSex(String sex) {
   
        this.sex = sex;
    }
}

package test1;

public class Pet {
   
    private String name;
    private int health;
    private int cute;

    public Pet(String name, int health, int cute) {
   
        this.name = name;
        this.health = health;
        this.cute = cute;
    }



    public void show(){
   
        System.out.println("宠物的自白:");
        System.out.println("我的名字:"+name+"\t"+"我的健康值为" +
                health+"\t"+"我和主人的亲密度是"+cute);
    }



    public String getName() {
   
        return name;
    }

    public void setName(String name) {
   
        this.name = name;
    }

    public int getHealth() {
   
        return health;
    }

    public void setHealth(int health) {
   
        this
  • 2
    点赞
  • 5
    收藏
    觉得还不错? 一键收藏
  • 3
    评论
评论 3
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值