测试说明
测试输入:泰迪
male
brown
波斯猫
male
2.5
预期输出:名称:泰迪,性别:male,颜色:brown,汪汪叫
泰迪吃骨头!
名称:波斯猫,性别:male,体重:2.5kg,喵喵叫
波斯猫吃鱼!
开始你的任务吧,祝你成功!
//package case1;
import java.util.Scanner;
public class Task1 {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
String dogName = sc.next();
String dogSex = sc.next();
String dogColor = sc.next();
String catName = sc.next();
String catSex = sc.next();
double catWeight = sc.nextDouble();
// 通过有参构造函数实例化Dog类对象dog
// dog调用talk()方法
// dog调用eat()方法
/********* begin *********/
Dog dog=new Dog(dogName,dogSex,dogColor);
System.out.print(dog.toString());
dog.talk();
dog.eat();
/********* end *********/
// 通过有参构造函数实例化Cat类对象cat
// cat调用talk()方法
// cat调用eat()方法
/********* begin *********/
Cat cat=new Cat(catName,catSex,catWeight);
System.out.print(cat.toString());
cat.talk();
cat.eat();
/********* end *********/
}
}
// 抽象类Pet 封装属性name和sex
// 构造函数初始化name和sex
// 声明抽象方法talk()
// 声明抽象方法eat()
abstract class Pet {
/********* begin *********/
private String name;
private String sex;
public Pet(String name, String sex) {
super();
this.name = name;
this.sex = sex;
}
public String getName() {
return name;
}
public String getSex() {
return sex;
}
abstract void talk();
abstract void eat();
/********* end *********/
}
// Dog类继承自Pet类 封装属性color
// 构造函数初始化name、sex和color
// 实现自己的talk()方法和eat()方法
// talk()输出'名称:name,性别:sex,颜色:color,汪汪叫'
// eat()输出'name吃骨头'
class Dog extends Pet {
private String color;
public Dog(String name, String sex, String color) {
super(name, sex);
this.color = color;
}
void talk() {
// TODO Auto-generated method stub
System.out.println("汪汪叫");
}
void eat() {
// TODO Auto-generated method stub
System.out.println(getName()+"吃骨头!");
}
public String getColor() {
return color;
}
public String toString() {
return String.format("名称:%s,性别:%s,颜色:%s,",getName(),getSex(),color);
}
}
// Cat类继承自Pet类 封装属性weight
// 构造函数初始化name、sex和weight
// 实现自己的talk()方法和eat()方法
// talk()输出'名称:name,性别:sex,体重:weight kg,喵喵叫'
// eat()输出'name吃鱼'
class Cat extends Pet {
private double weight;
public Cat(String name, String sex, double weight) {
super(name, sex);
this.weight=weight;
}
void talk() {
// TODO Auto-generated method stub
System.out.println("喵喵叫");
}
void eat() {
// TODO Auto-generated method stub
System.out.println(getName()+"吃鱼!");
}
public double getWeight() {
return weight;
}
public String toString() {
return String.format("名称:%s,性别:%s,体重:%.1fkg,",getName(),getSex(),weight);
}
}