/**
創(chuàng)新互聯(lián)公司專業(yè)為企業(yè)提供青銅峽網(wǎng)站建設(shè)、青銅峽做網(wǎng)站、青銅峽網(wǎng)站設(shè)計(jì)、青銅峽網(wǎng)站制作等企業(yè)網(wǎng)站建設(shè)、網(wǎng)頁(yè)設(shè)計(jì)與制作、青銅峽企業(yè)網(wǎng)站模板建站服務(wù),十年青銅峽做網(wǎng)站經(jīng)驗(yàn),不只是建網(wǎng)站,更提供有價(jià)值的思路和整體網(wǎng)絡(luò)服務(wù)。
* 1.定義一個(gè)水果類Fruit,符合如下要求:
(a) 類Fruit的成員變量;
weight表示水果的質(zhì)量,數(shù)據(jù)類型為float
color表示水果的顏色,數(shù)據(jù)類型為string.
(b)類Fruit的成員方法:
getWeight()獲得水果的質(zhì)量
getColor()獲得水果的顏色
2、按照第1題中的水果類Fruit的定義,創(chuàng)建該類的對(duì)象f1和f2,其中f1的weight值為0.86, color值為yellow;
f2的weight值為0.73, color值為red; 存儲(chǔ)并輸出f1和f2的值,計(jì)算f1和f2的平均值。
* @author Administrator
*
*/
public class Fruit {
private float weight;
private String color;
//構(gòu)造函數(shù):用于存儲(chǔ)對(duì)象的2個(gè)值
public Fruit(float weight, String color){
this.weight = weight;
this.color = color;
}
public float getWeight() {
return this.weight;
}
public String getColor() {
return this.color;
}
//求重量的平均值
public static float avg(float w1, float w2){
return w1*w2/2;
}
public static void main(String[] args){
Fruit f1 = new Fruit((float) 0.86, "yellow");
Fruit f2 = new Fruit((float) 0.73, "red");
System.out.println("f1:" + "\n" + " weitht:" + f1.getWeight() + "\n" + " color:" + f1.getColor());
System.out.println("f2:" + "\n" + " weitht:" + f2.getWeight() + "\n" + " color:" + f2.getColor());
System.out.println("平均值:" + Fruit.avg(f1.getWeight(), f2.getWeight()));
}
}
class?Fruit{
private?String?fruitName;
private?float?price;
public?Fruit(String?fruitName,?float?price)?{
super();
this.fruitName?=?fruitName;
this.price?=?price;
}
public?String?getFruitName()?{
return?fruitName;
}
public?void?setFruitName(String?fruitName)?{
this.fruitName?=?fruitName;
}
public?float?getPrice()?{
return?price;
}
public?void?setPrice(float?privce)?{
this.price?=?privce;
}
@Override
public?String?toString()?{
return?"水果名稱:"?+?getFruitName()?+?"???????"?+?"價(jià)格:"?+?getPrice();
}
}
class?Apple?extends?Fruit{
public?Apple(String?fruitName,?float?price)?{
super(fruitName,?price);
}
}
class?Banana?extends?Fruit{
public?Banana(String?fruitName,?float?price)?{
super(fruitName,?price);
}
}
public?class?FruitShop?{
ListFruit?list;
public?FruitShop(){
list?=?new?ArrayListFruit();
list.add(new?Apple("蘋果",3));
list.add(new?Banana("香蕉",2));
}
public?void?show(){
for?(Fruit?f?:?list)?{
System.out.println(f);
}
}
public?static?void?main(String[]?args)?{
new?FruitShop().show();
}
}
public class Fruit {
private String name;
private double weight;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public double getWeight() {
return weight;
}
public void setWeight(double weight) {
this.weight = weight;
}
//構(gòu)造方法
public Fruit(String name,double weight){
this.name = name;
this.weight = weight;
}
/**
* @param args
*/
public static void main(String[] args) {
// TODO Auto-generated method stub
Fruit f = new Fruit("蘋果",0.5);
System.out.println(f.getName());//輸出名稱
System.out.println(f.getWeight());//輸出名稱
}
}
如果對(duì)你有所幫助,請(qǐng)采納,謝謝!