java鸭子玩具店类体系设计与实现
时间: 2024-12-22 08:18:30 浏览: 7
在Java中,鸭子玩具店的设计通常涉及到面向对象编程,特别是继承、封装和多态等原则。我们可以创建一个“鸭子”(Duck)类作为基础模型,然后通过继承创建不同种类的鸭子(如普通鸭子、会飞的鸭子或不会飞但游泳好的鸭子)。
以下是简化的类体系设计:
```java
// 基础鸭子类
class Duck {
private String name;
private boolean canFly;
public Duck(String name, boolean canFly) {
this.name = name;
this.canFly = canFly;
}
// 公共行为方法
public void quack() {
System.out.println("Quack! (" + name + ")");
}
public void swim() {
if (canFly) {
System.out.println(name + " swims like a real duck.");
} else {
System.out.println(name + " is a great swimmer!");
}
}
}
// 特定种类的鸭子继承自基础鸭子
class FlyingDuck extends Duck {
public FlyingDuck(String name) {
super(name, true);
}
@Override
public void fly() {
System.out.println(name + " flies in the sky.");
}
}
class SwimmingDuck extends Duck {
public SwimmingDuck(String name) {
super(name, false);
}
}
// 玩具店类
class ToyShop {
public void introduceDuck(Duck duck) {
duck.quack();
duck.swim();
if (duck instanceof FlyingDuck) {
((FlyingDuck) duck).fly();
}
}
}
public class Main {
public static void main(String[] args) {
ToyShop shop = new ToyShop();
Duck regularDuck = new Duck("Regular Duck", true);
FlyingDuck flyingDuck = new FlyingDuck("Fancy Flyer");
SwimmingDuck swimmingDuck = new SwimmingDuck("Strong Swimmer");
shop.introduceDuck(regularDuck);
shop.introduceDuck(flyingDuck);
shop.introduceDuck(swimmingDuck);
}
}
```
在这个例子中,`ToyShop`负责展示各种鸭子的行为,而鸭子种类的差异通过覆盖方法来体现多态性。
阅读全文