/** * 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,我是一只没有智商的哈士奇
java继承案例(Pet、Dog、Penguin)
最新推荐文章于 2026-04-19 04:47:51 发布
本文展示了一个简单的Java程序,该程序通过继承机制创建了Penguin(企鹅)和Dog(狗)两个宠物类,并实现了sayHello方法来展示每个宠物的基本信息。
&spm=1001.2101.3001.5002&articleId=70761523&d=1&t=3&u=6fd4c9e7317a49e188323ffe61a8f4a8)
2233

被折叠的 条评论
为什么被折叠?



