欢迎来到尧图网

客户服务 关于我们

您的位置:首页 > 新闻 > 社会 > Java继承练习(1) (2024.7.9)

Java继承练习(1) (2024.7.9)

2025/1/21 9:57:25 来源:https://blog.csdn.net/Aishangyuwen/article/details/140309338  浏览:    关键词:Java继承练习(1) (2024.7.9)

        动物继承

        动物类

package Animal20240709;public class Animal {int age;String color;public Animal() {}public Animal(int age, String color) {this.age = age;this.color = color;}public int getAge() {return age;}public void setAge(int age) {this.age = age;}public String getColor() {return color;}public void setColor(String color) {this.color = color;}public void eat(String eatThing) {System.out.printf("颜色为%s的%d岁动物在吃%s\n", this.color, this.age, eatThing);}
}

        狗类

package Animal20240709;public class Dog extends Animal{public Dog() {}public Dog(int age, String color) {super(age, color);}@Overridepublic void eat(String eatThing) {System.out.printf("颜色为%s的%d岁狗在吃%s\n", this.color, this.age, eatThing);}
}

        猫类

package Animal20240709;public class Cat extends Animal{public Cat() {}public Cat(int age, String color) {super(age, color);}@Overridepublic void eat(String eatThing) {System.out.printf("颜色为%s的%d岁猫在吃%s\n", this.color, this.age, eatThing);}
}

        人类

package Animal20240709;public class Person {String name;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.printf("%d岁的主人%s在喂%d岁的%s狗吃%s\n", this.age, this.name,dog.age, dog.color, something);}public void keepPet(Cat cat,String something) {System.out.printf("%d岁的主人%s在喂%d岁的%s哈基米吃%s\n", this.age, this.name,cat.age, cat.color, something);}
}

        测试

package Animal20240709;
import java.util.Scanner;
public class AnimalTest {public static void main(String[] args) {Scanner sc = new Scanner(System.in);System.out.println("请输入主人的名字");String name = sc.next();System.out.println("请输入主人的年龄");int age = sc.nextInt();Person p = new Person(name, age);System.out.println("请输入狗的毛色");String dogColor = sc.next();System.out.println("请输入狗的年龄");int dogAge = sc.nextInt();Dog d = new Dog(dogAge, dogColor);System.out.println("请输入猫的毛色");String catColor = sc.next();System.out.println("请输入猫的年龄");int catAge = sc.nextInt();Cat c = new Cat(catAge, catColor);p.keepPet(d, "骨头");p.keepPet(c, "fish");d.eat("骨头");c.eat("fish");}
}

 

 

 

 

版权声明:

本网仅为发布的内容提供存储空间,不对发表、转载的内容提供任何形式的保证。凡本网注明“来源:XXX网络”的作品,均转载自其它媒体,著作权归作者所有,商业转载请联系作者获得授权,非商业转载请注明出处。

我们尊重并感谢每一位作者,均已注明文章来源和作者。如因作品内容、版权或其它问题,请及时与我们联系,联系邮箱:809451989@qq.com,投稿邮箱:809451989@qq.com