用JAVA语言设计一个猫/狗类,设计其相应的属性和方法。 2、创建类的对象,并调用相应的属性和方法。
时间: 2024-05-23 22:16:41 浏览: 16
很高兴为您解答。以下是我对您的问题的回答:
1. 用JAVA语言设计一个猫/狗类,设计其相应的属性和方法:
可以参考下面的代码:
public class Pet {
private String type;
private String name;
private int age;
public Pet(String type, String name, int age) {
this.type = type;
this.name = name;
this.age = age;
}
public String getType() {
return type;
}
public String getName() {
return name;
}
public int getAge() {
return age;
}
public void setType(String type) {
this.type = type;
}
public void setName(String name) {
this.name = name;
}
public void setAge(int age) {
this.age = age;
}
public void eat() {
System.out.println(name + " is eating.");
}
public void sleep() {
System.out.println(name + " is sleeping.");
}
public void play() {
System.out.println(name + " is playing.");
}
}
public class Cat extends Pet {
public Cat(String name, int age) {
super("cat", name, age);
}
@Override
public void play() {
System.out.println(getName() + " is playing with a mouse.");
}
}
public class Dog extends Pet {
public Dog(String name, int age) {
super("dog", name, age);
}
@Override
public void play() {
System.out.println(getName() + " is playing with a ball.");
}
}
2. 创建类的对象,并调用相应的属性和方法:
可以参考下面的代码:
public class Test {
public static void main(String[] args) {
Cat cat = new Cat("Kitty", 2);
Dog dog = new Dog("Jack", 3);
System.out.println(cat.getName() + " is a " + cat.getType() + " and is " + cat.getAge() + " years old.");
System.out.println(dog.getName() + " is a " + dog.getType() + " and is " + dog.getAge() + " years old.");
cat.eat();
cat.sleep();
cat.play();
dog.eat();
dog.sleep();
dog.play();
}
}
输出结果:
Kitty is a cat and is 2 years old.
Jack is a dog and is 3 years old.
Kitty is eating.
Kitty is sleeping.
Kitty is playing with a mouse.
Jack is eating.
Jack is sleeping.
Jack is playing with a ball.