目录
💴哈喽,大家好丫,你们的小郭子又来啦 ~
🌞今天我们用java来写一个简单的小项目——【点餐商店】,嘿嘿
🌞话不多说,直接上干货,
(一)功能和效果
(二)代码实现
(1)披萨父类
public class Pizza {
//属性
private String name;//名称
private int size;//大小
private int price;//价格
//方法
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getSize() {
return size;
}
public void setSize(int size) {
this.size = size;
}
public int getPrice() {
return price;
}
public void setPrice(int price) {
this.price = price;
}
//展示匹萨信息:
public String showPizza(){
return "匹萨的名字是:"+name+"\n匹萨的大小是:"+size+"寸\n匹萨的价格:"+price+"元";
}
//构造器
public Pizza() {
}
public Pizza(String name, int size, int price) {
this.name = name;
this.size = size;
this.price = price;
}
}
-
(2)培根披萨
-
public class BaconPizza extends Pizza { //属性: private int weight; public int getWeight() { return weight; } public void setWeight(int weight) { this.weight = weight; } //构造器: public BaconPizza() { } public BaconPizza(String name, int size, int price, int weight) { super(name, size, price); this.weight = weight; } //重写父类showPizza方法: @Override public String showPizza() { return super.showPizza()+"\n培根的克数是:"+weight+"克"; } }
(3)水果披萨
-
public class FruitsPizza extends Pizza{ //属性: private String burdening; public String getBurdening() { return burdening; } public void setBurdening(String burdening) { this.burdening = burdening; } //构造器: public FruitsPizza() { } public FruitsPizza(String name, int size, int price, String burdening) { super(name, size, price); this.burdening = burdening; } //重写父类showPizza方法: @Override public String showPizza() { return super.showPizza()+"\n你要加入的水果:"+burdening; } }
(4)工厂类
-
public class PizzaStore { public static Pizza getPizza(int choice){ Scanner sc = new Scanner(System.in); Pizza p = null; switch (choice){ case 1: { System.out.println("请录入培根的克数:"); int weight = sc.nextInt(); System.out.println("请录入匹萨的大小:"); int size = sc.nextInt(); System.out.println("请录入匹萨的价格:"); int price = sc.nextInt(); //将录入的信息封装为培根匹萨的对象: BaconPizza bp = new BaconPizza("培根匹萨",size,price,weight); p = bp; } break; case 2: { System.out.println("请录入你想要加入的水果:"); String burdening = sc.next(); System.out.println("请录入匹萨的大小:"); int size = sc.nextInt(); System.out.println("请录入匹萨的价格:"); int price = sc.nextInt(); //将录入的信息封装为水果匹萨的对象: FruitsPizza fp = new FruitsPizza("水果匹萨",size,price,burdening); p = fp; } break; } return p; } }
(5)测试类
-
public class Test { public static void main(String[] args) { //选择购买匹萨: Scanner sc = new Scanner(System.in); System.out.println("请选择你想要购买的匹萨(1.培根匹萨 2.水果匹萨):"); int choice = sc.nextInt();//选择 //通过工厂获取匹萨: Pizza pizza = PizzaStore.getPizza(choice); System.out.println(pizza.showPizza()); } }
好啦,今天的分享到这里就结束啦 ~🌞🌞
觉得我分享的文章不错的话,可以关注一下哦,嘻嘻嘻🌞🌞
-
版权声明:本文内容由互联网用户自发贡献,该文观点仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 举报,一经查实,本站将立刻删除。
文章由极客之音整理,本文链接:https://www.bmabk.com/index.php/post/73231.html