(1)
public class animal {
private String color;
private int age;
public animal() {
}
public animal(String color, int age) {
this.color = color;
this.age = age;
}
public String getColor() {
return color;
}
public void setColor(String color) {
this.color = color;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
public void eat(String something){
System.out.println("在吃"+something);
}
}
(2)
public class cat extends animal{
public cat(String 黑) {
}
public cat(String color, int age) {
super(color, age);
}
@Override
public void eat(String something) {
System.out.println(getAge()+"岁的"+getColor()+"在吃"+something);
}
public void zhualaoshu(){
System.out.println("猫抓老鼠");
}
}
(3)
public class dog extends animal{
public dog() {
}
public dog(String color, int age) {
super(color, age);
}
@Override
public void eat(String something) {
System.out.println(getAge()+"岁的"+getColor()+"颜色的狗在抱住"+something+"吃骨头");
}
public void lookhome(){
System.out.println("狗在看家");
}
}
(4)
public class person {
private String name;
private int age;
public person() {
}
public person(String name, int age) {
this.name = name;
this.age = age;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
/*public void keeppet(dog dog,String something){
System.out.println("年龄为"+age+"岁的"+name+"养了一只"+dog.getColor()+"颜色的"+dog.getAge()+"岁的狗");
dog.eat(something);
}
public void keeppet(cat cat,String something){
System.out.println("年龄为"+age+"岁的"+name+"养了一只"+cat.getColor()+"颜色的"+cat.getAge()+"岁的猫");
cat.eat(something);
}*/
public void keeppet(animal a,String something){
if(a instanceof dog d){
System.out.println("年龄为"+age+"岁的"+name+"养了一只"+a.getColor()+"颜色的"+a.getAge()+"岁的狗");
d.eat(something);
} else if (a instanceof cat c) {
System.out.println("年龄为"+age+"岁的"+name+"养了一只"+c.getColor()+"颜色的"+c.getAge()+"岁的猫");
c.eat(something);
}else {
System.out.println("没有这种动物");
}
}
}
(5)
public class test {
/*public static void main(String[] args) {
person l=new person("liujiawei",18);
dog d=new dog("白",2);
l.keeppet(d,"骨头");
System.out.println();
person n=new person("nazale",18);
cat c=new cat();
n.keeppet(c,"鱼");
}*/
public static void main(String[] args) {
person l=new person("liujiawei",18);
dog d=new dog("白",2);
l.keeppet(d,"骨头");
cat c=new cat("黑",3);
l.keeppet(c,"鱼");
}
}