01-19作业
1、创建父类:
package chongwu0118;
//父类创建
public class Chongwu {
//宠物名
private String name;
//健康值
private int heath;
//亲密度
private int love;
//get/set方法
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getHeath() {
return heath;
}
public void setHeath(int heath) {
if(heath<0||heath>100) {
this.heath=60;
System.out.println("健康值在0~100之间,输入错误,默认60");
}else {
this.heath=heath;
}
}
public int getLove() {
return love;
}
public void setLvoe(int love) {
if(love<0||love>100) {
this.love=60;
System.out.println("亲密度在0~100,输入错误,默认60");
}else {
this.love = love;}
}
public void prin() {
System.out.println("宠物自白:");
System.out.println("我的姓名是:"+getName()+"健康值为:"+getHeath()+"亲密度为:"+getLove());
}
}
2、子类--狗狗类
package chongwu0118;
//子类 狗狗类
public class Dog extends Chongwu{
//狗狗品种
private String bree;
public String getBree() {
return bree;
}
public void setBree(String bree) {
this.bree = bree;
}
public void print() {
super.prin();
System.out.println("我是"+this.bree);
}
}
3、子类--猫类:
package chongwu0118;
//子类 猫类
public class Cat extends Chongwu{
//猫的颜色
private String colour;
public String getColour() {
return colour;
}
public void setColour(String colour) {
this.colour=colour;
}
public void print() {
super.prin();
System.out.println("我的颜色是:"+this.colour);
}
}
4、子类--企鹅类
package chongwu0118;
//子类 企鹅类
public class Penguin extends Chongwu{
//企鹅性别
private String sex;
public String getSex() {
return sex;
}
public void setSex(int sex) {
if(sex==1) {
this.sex="Q仔";
}else {
this.sex="Q妹";
}
}
public void print() {
super.prin();
System.out.println("我的性别是:"+this.sex);
}
}
5、主程序:
package chongwu0118;
import java.util.Scanner;
//主程序
public class Test {
public static void main(String[] args) {
Scanner cw=new Scanner(System.in);
Dog dog = new Dog();
Cat cat = new Cat();
Penguin pen = new Penguin();
System.out.println("欢迎来到宠物店");
System.out.println("请输入您要领养的宠物名字:");
String name=cw.next();
System.out.println("请输入您要领养的宠物类型:1、狗 2、猫 3、企鹅:");
int select =cw.nextInt();
switch(select){
case 1:
dog.setName(name);
System.out.println("请选择狗狗的健康值:");
dog.setHeath(cw.nextInt());
System.out.println("请输入狗狗的亲密度:");
dog.setLvoe(cw.nextInt());
System.out.println("请输入狗狗的品种:");
dog.setBree(cw.next());
dog.print();
break;
case 2:
cat.setName(name);
System.out.println("请选择猫的健康值:");
cat.setHeath(cw.nextInt());
System.out.println("请输入猫的亲密度:");
cat.setLvoe(cw.nextInt());
System.out.println("请输入猫的颜色:");
cat.setColour(cw.next());
cat.print();
break;
case 3:
pen.setName(name);
System.out.println("请选择企鹅的健康值:");
pen.setHeath(cw.nextInt());
System.out.println("请输入企鹅的亲密度:");
pen.setLvoe(cw.nextInt());
System.out.println("请输入企鹅的性别:1、Q仔 2、Q妹");
pen.setSex(cw.nextInt());
pen.print();
break;
default:
System.out.println("您的输入有误!");
}
}
}
6、输出结果:

百度网盘:
链接:https://pan.baidu.com/s/1Rjp_8g0uute7g4uLLvXk6w
提取码:e6bb
复制这段内容后打开百度网盘手机App,操作更方便哦

浙公网安备 33010602011771号