编写程序实现比萨制作。需求说明编写程序,接收用户输入的信息,选择需要制作的比萨。可供选择的比萨有:培根比萨和海鲜比萨。
实现思路及关键代码
1)分析培根比萨和海鲜比萨
2)定义比萨类
3)属性:名称、价格、大小
4)方法:展示
5)定义培根比萨和海鲜比萨继承自比萨类
6)定义比萨工厂类,根据输入信息产生具体的比萨对象
Pizza.java
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
|
package zuoye;
import java.util.Scanner;
//父类
public class Pizza {
String name;
double price;
int size;
public Pizza(String name){
this .name=name;
}
public void display(){
Scanner sc= new Scanner(System.in);
System.out.println( "请输入披萨大小:" );
size=sc.nextint();
System.out.println( "请输入披萨价格:" );
price=sc.nextdouble();
}
}
|
PeiGen.java
1
2
3
4
5
6
7
8
9
10
11
12
13
14
|
package zuoye;
import java.util.Scanner;
//子类培根披萨
public class PeiGen extends Pizza {
// double weight;
public PeiGen(String name) {
super (name);
}
public double peigen() {
System.out.println( "输入培根克数:" );
Scanner s = new Scanner(System.in);
return s.nextdouble();
}
}
|
SeaFood.java
1
2
3
4
5
6
7
8
9
10
11
12
13
14
|
package zuoye;
import java.util.Scanner;
//子类海鲜披萨
public class SeaFood extends Pizza{
public SeaFood(String name) {
super (name);
}
public String seafood() {
System.out.println( "输入配料信息:" );
Scanner s= new Scanner(System.in);
String peiliao=s.next();
return peiliao;
}
}
|
Work.java
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
|
package zuoye;
import java.util.Scanner;
public class Work {
public static void main(String[] args) {
System.out.println( "请选择想要的披萨(1.培根披萨 2.海鲜披萨)" );
Scanner s = new Scanner(System.in);
int n = s.nextint();
if (n == 1 ) {
PeiGen pg = new PeiGen( "培根披萨" );
double b=pg.peigen();
pg.display();
System.out.println( "名称" + pg.name + "\n价格:" + pg.price + "\n大小:" + pg.size + "\n培根克数:" +b);
} else if (n == 2 ) {
SeaFood sf = new SeaFood( "海鲜披萨" );
String a=sf.seafood();
sf.display();
System.out.println( "名称" + sf.name + "\n价格:" + sf.price + "\n大小:" + sf.size + "\n配料:" +a);
}
}
}
|
结果展示:
总结
以上就是本文关于java子类继承父类实例-披萨的选择实现代码的全部内容,希望对大家有所帮助。如有不足之处,欢迎留言指出。感谢朋友们对本站的支持!
原文链接:http://blog.csdn.net/u012060033/article/details/76098807