本项目锻炼技能:面向对象 ( 继承 封装 多态 简单工厂模式)
-
项目需求:
源代码:
//父类的pizza
public class Pizza {
//父类共有的属性
//名称
private String name;
//尺寸
private int size;
//价格
private int price;
//父类的构造器
public Pizza(String name, int size, int price) {
this.name = name;
this.size = size;
this.price = price;
}
public Pizza() {
}
//getter setter方法
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 void showInformation(){
System.out.println("名称:"+this.name+"\n"+"价格:"+this.price+"元\n"+"大小:"+this.size+"寸");
}
}
//子类:培根pizza
public class BacconPizza extends Pizza {
//子类特有的属性
//克数
private int kg;
//构造方法
public BacconPizza(String name, int size, int price, int kg) {
super(name, size, price);
this.kg = kg;
}
public BacconPizza() {
}
//getter setter方法
public int getKg() {
return kg;
}
public void setKg(int kg) {
this.kg = kg;
}
//对父类显示方法的重写
@Override
public void showInformation() {
super.showInformation();
System.out.println("培根克数:"+this.kg+"g");
}
}
//子类:fruit类
public class FruitPizza extends Pizza {
//水果pizza特有的属性
//想要加入的水果
private String conponent;
//构造器
public FruitPizza(String name, int size, int price, String conponent) {
super(name, size, price);
this.conponent = conponent;
}
public FruitPizza() {
}
//getter,setter方法
public String getConponent() {
return conponent;
}
public void setConponent(String conponent) {
this.conponent = conponent;
}
//重写父类展示的方法
@Override
public void showInformation() {
super.showInformation();
System.out.println("水果配料:"+conponent);
}
}
//制造pizza的工厂类
public class PizzaStory {
public static Pizza producePizza(int select){
Pizza p=null;
Scanner sc=new Scanner(System.in);
switch (select){
case 1:
System.out.print("请输入培根的克数:");
int kg = sc.nextInt();
System.out.print("请输入披萨的大小:");
int size = sc.nextInt();
System.out.print("请输入披萨的价格:");
int price = sc.nextInt();
p=new BacconPizza("培根披萨",size,price,kg);
break;
case 2:
System.out.print("请输入你想要加入的水果:");
String conponent = sc.next();
System.out.print("请输入披萨的大小:");
int size1 = sc.nextInt();
System.out.print("请输入披萨的价格:");
int price1 = sc.nextInt();
p=new FruitPizza("水果披萨",size1,price1,conponent);
break;
default:
break;
}
return p;
}
}
//test测试类
public class Test {
public static void main(String[] args) {
System.out.print("请选择要制作的披萨:1.培根披萨 2.水果披萨:");
Scanner sc=new Scanner(System.in);
int select=sc.nextInt();//选择披萨
//提出需求,披萨工厂开始制作披萨。
Pizza pizza = PizzaStory.producePizza(select);
pizza.showInformation();
}
}
-
运行结果: