java继承优化电子宠物
时间: 2023-09-22 19:06:05 浏览: 155
对于电子宠物这样的应用程序,可以考虑使用面向对象编程中的继承来优化代码。
首先,定义一个基类Pet,包含宠物的一些通用属性和方法,比如名字、年龄、体重、喂食、运动等。
然后,可以定义不同种类的宠物,比如Dog、Cat、Fish等,它们都继承自Pet类,并可以添加自己特有的属性和方法,比如不同种类的宠物可以有不同的叫声、喜欢的玩具等。
在实现继承时,可以使用Java中的extends关键字,如下所示:
```java
public class Pet {
protected String name;
protected int age;
protected double weight;
public void feed() {
System.out.println("Feeding " + name + "...");
}
public void play() {
System.out.println("Playing with " + name + "...");
}
}
public class Dog extends Pet {
private String barkSound;
public Dog(String name, int age, double weight, String barkSound) {
this.name = name;
this.age = age;
this.weight = weight;
this.barkSound = barkSound;
}
public void bark() {
System.out.println(name + " barks: " + barkSound);
}
}
public class Cat extends Pet {
private String meowSound;
public Cat(String name, int age, double weight, String meowSound) {
this.name = name;
this.age = age;
this.weight = weight;
this.meowSound = meowSound;
}
public void meow() {
System.out.println(name + " meows: " + meowSound);
}
}
public class Fish extends Pet {
private String swimStyle;
public Fish(String name, int age, double weight, String swimStyle) {
this.name = name;
this.age = age;
this.weight = weight;
this.swimStyle = swimStyle;
}
public void swim() {
System.out.println(name + " swims: " + swimStyle);
}
}
```
这样,我们可以创建不同种类的宠物对象,并对其进行操作:
```java
public class Main {
public static void main(String[] args) {
Dog dog = new Dog("Buddy", 2, 10.5, "Woof woof!");
Cat cat = new Cat("Fluffy", 3, 5.8, "Meow meow!");
Fish fish = new Fish("Goldie", 1, 0.3, "Freestyle");
dog.feed();
cat.play();
fish.swim();
dog.bark();
cat.meow();
}
}
```
这样的设计可以使代码更加清晰、易于维护和扩展。
阅读全文