教育路上
摘要:用繼承的方式創建一個水果類,有成員變量:重量和單價,有成員方法:計算水果的總價格并顯示。以下是我們為大家整理的,相信大家閱讀完后肯定有了自己的選擇吧。
2023-02-08 15:27網絡推薦
1、創建一個水果類,有成員變量:重量和單價,有成員方法:計算水果的總價格并顯示:單價*重量。
2、創建一個蘋果類,繼承水果類,繼承水果計算總價格方法,
3、創建一個西瓜類,繼承水果類,重寫父類的計算水果的方法,按照2倍單價計算總價:2*單價*重量
創建一個具體的蘋果對象:蘋果單價5元、8斤,并顯示對象的總價格
創建一個具體的西瓜對象:西瓜單價3元、5斤,并計算對象的總價格
注意:必須用類的繼承方式完成本題。否則一律打回作業。
在主類里面對輸入的蘋果或西瓜進行判定,然后創建相應的對象,提示:判定方法:if(fruitnameequals("蘋果")),會返回一個邏輯值
import javautilScanner;
class Fruit
{
Fruit(){}
Fruit(String name, int price,int weight){
thisname=name;
thisweight=weight;
thisprice=price;
}
String name;
int weight;
int price;
public void show()
{
Systemoutprintln(name+"總價"+weight*price);
}
}
class Apple extends Fruit { }
class Watermelon extends Fruit{
public void show() {
Systemoutprintln(name+"總價"+2*weight*price);
}
}
public class Main {
public static void main(String[] args)
{
Scanner input = new Scanner(Systemin);
Fruit fruit=new Fruit();
Apple apple=new Apple();
Watermelon watermelon=new Watermelon();
String fruitname = inputnext();
if(fruitnameequals("蘋果")) {
Apple p1=new Apple();
p1name=fruitname;
p1price=inputnextInt();
p1weight=inputnextInt();
p1show();
}
else if(fruitnameequals("西瓜")) {
Watermelon p1=new Watermelon();
p1name=fruitname;
p1price=inputnextInt();
p1weight=inputnextInt();
p1show();
}
} }
訪客的評論 2023/11/08 20:51
文中描述的是準確的嗎,如何報名!