java继承案例(Pet、Dog、Penguin)

来源:互联网 发布:更改windows系统语言 编辑:程序博客网 时间:2024/05/29 08:55
/** * Created by Administrator on 2017/4/25. */public class Main {    public static void main(String[] args) {        Penguin penguin = new Penguin();        System.out.println(penguin.sayHello());        Dog dog = new Dog();        System.out.println(dog.sayHello());    }

}

public class Pet {    public String name;    public int healthy;    public int intimacy;    public String sayHello(){        return "";    }}
public class Penguin extends Pet {    private String sex;    public Penguin(){        this.name="欧欧";        this.healthy=100;        this.sex="Q妹";        this.intimacy=0;    }    public String sayHello(){        String hello="宠物的自白:\n";        hello+= "我的名字叫"+this.name+",我的健康值是"+this.healthy+                ",我和主人的亲密度是"+this.intimacy+",我的性别是"+this.sex;        return hello;    }}
public class Dog extends Pet {    private String dogclass;    public Dog(){        this.name="花花";        this.healthy=100;        this.intimacy=50;        this.dogclass="没有智商的哈士奇";    }    public String sayHello(){        String hello="宠物的自白:\n";         hello+= "我的名字叫"+super.name+",我的健康值是"+super.healthy+                 ",我和主人的亲密度是"+super.intimacy+",我是一只"+this.dogclass;        return hello;    }}

运行结果:
宠物的自白:我的名字叫欧欧,我的健康值是100,我和主人的亲密度是0,我的性别是Q妹宠物的自白:我的名字叫花花,我的健康值是100,我和主人的亲密度是50,我是一只没有智商的哈士奇

0 0
原创粉丝点击