栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > Java

多态练习代码

Java 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

多态练习代码

前面练习代码忘了发了,再发一下!
package Ex01;

import java.util.Scanner;


public class Pet {
    String name;
    int health;
    @Override
    public String toString() {  //重写的toString()方法
        return name +"health="+ health;
    }

    void eat() {
    }
}

class Dog extends Pet {
    public Dog() {
        this.name = "狗狗";
        this.health = 80;
    }

    void skill(){  //狗狗特有技能
        System.out.println("我是狗狗,我可以接飞盘!");
    }
    void eat() {
        this.health += 3;
        if (this.health >= 100) {
            this.health = 100;
        }
    }
}

class Penguin extends Pet {
    public Penguin() {
        this.name = "企鹅";
        this.health = 80;
    }
    void skill(){  //企鹅特有技能
        System.out.println("我是企鹅,我可以在南极游泳!");
    }
    void eat() {
        this.health += 5;
        if (this.health >= 100) {
            this.health = 100;
        }
    }
}
class Master {
    void giveFood(Pet a) {
        a.eat();
    }
    public static void main(String[] args) {
        Master m = new Master();
        Pet d = new Dog();//向上转型
        Pet p = new Penguin();//向上转型
        if(d instanceof Dog)//用于判断d是否是Dog的实例
            ((Dog) d).skill() ;//向下转型,执行Dog的特有技能
        if(p instanceof Penguin)//用于判断p是否是Penguin的实例
            ((Penguin) p).skill();//向下转型,执行penguin的特有技能
        m.giveFood(d);//主人给d喂食
        m.giveFood(p);//主人给p喂食
        System.out.println(d.toString());
        System.out.println(p.toString());
    }
}

package Ex01;

import java.util.Scanner;


public class Human {
    public void printGoods(Goods s){
        System.out.println(s.name+"的价格为:"+s.price);
    }
    public static void main(String[] args) {
        Goods a=new TVs("电视机",5000);
        Goods b=new Foods("奶粉",200);
        Human h=new Human();
        h.printGoods(a);
        h.printGoods(b);
    }
}

class Goods {
    String name;
    double price;
}

class TVs extends Goods{
    public TVs( String a, double b) {
        this.name=a;
        this.price=b;
    }
}
class Foods extends Goods{
    public Foods(String a, double b) {
        this.name=a;
        this.price=b;
    }
}
转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/425577.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号