使用Java语言面向对象实现蛋糕店 1.定义抽象蛋糕类(Cake)(1.成员变量(名称、尺寸、价格)2.构造方法 3.get/set方法 4.show()方法用来展示信息 5.写一个抽象方法suggest()); 2.定义水果蛋糕类(FruitCake),继承抽象蛋糕类(Cake),定义变量水果材料Material; 3. 定义巧克力蛋糕类(ChocolateCake),继承抽象蛋糕类(Cake), 定义变量巧克力重量weight 4. 定义测试类,编写主界面,用Scanner输入数据,用switch进行选择判断,编写俩个方法进行调用。
时间: 2024-03-14 14:46:12 浏览: 96
好的,让我来解答一下你的问题。
以下是Java语言面向对象实现蛋糕店的代码:
1.定义抽象蛋糕类(Cake)
```java
public abstract class Cake {
private String name;
private double size;
private double price;
public Cake(String name, double size, double price) {
this.name = name;
this.size = size;
this.price = price;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public double getSize() {
return size;
}
public void setSize(double size) {
this.size = size;
}
public double getPrice() {
return price;
}
public void setPrice(double price) {
this.price = price;
}
public void show() {
System.out.println("名称:" + name + ",尺寸:" + size + ",价格:" + price);
}
public abstract void suggest();
}
```
2.定义水果蛋糕类(FruitCake)
```java
public class FruitCake extends Cake {
private String material;
public FruitCake(String name, double size, double price, String material) {
super(name, size, price);
this.material = material;
}
public String getMaterial() {
return material;
}
public void setMaterial(String material) {
this.material = material;
}
@Override
public void suggest() {
System.out.println("该蛋糕推荐搭配" + material + "水果");
}
}
```
3.定义巧克力蛋糕类(ChocolateCake)
```java
public class ChocolateCake extends Cake {
private double weight;
public ChocolateCake(String name, double size, double price, double weight) {
super(name, size, price);
this.weight = weight;
}
public double getWeight() {
return weight;
}
public void setWeight(double weight) {
this.weight = weight;
}
@Override
public void suggest() {
System.out.println("该蛋糕推荐使用" + weight + "g的巧克力");
}
}
```
4.定义测试类,编写主界面,用Scanner输入数据,用switch进行选择判断,编写俩个方法进行调用。
```java
import java.util.Scanner;
public class CakeTest {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
System.out.println("欢迎来到蛋糕店!");
System.out.println("请选择您要购买的蛋糕类型:");
System.out.println("1. 水果蛋糕");
System.out.println("2. 巧克力蛋糕");
int choice = input.nextInt();
switch (choice) {
case 1:
FruitCake fruitCake = new FruitCake("水果蛋糕", 20, 88.88, "草莓");
fruitCake.show();
fruitCake.suggest();
break;
case 2:
ChocolateCake chocolateCake = new ChocolateCake("巧克力蛋糕", 18, 99.99, 200);
chocolateCake.show();
chocolateCake.suggest();
break;
default:
System.out.println("输入错误,请重新选择!");
}
input.close();
}
}
```
以上就是Java语言面向对象实现蛋糕店的代码,希望对你有所帮助!
阅读全文