java程序题:定义一个抽象类-水果,其中包括getWeight()方法,编写程序分别创建苹果、

定义一个抽象类-水果,其中包括getWeight()方法,编写程序分别创建苹果、桃子、橘子三个类,创建若干水果对象存放在一个水果类型的数组中,输出数组中所有水果的类型、重量。提示:利用对象的getClass().getName()方法可获取对象的所属类的名称。

水果类

abstract public class Fruit {
abstract public double getWeight();
}


苹果类

public class Apple extends Fruit {
private double weight;

public Apple(double weight) {
this.weight = weight;
}

@Override
public double getWeight() {
return weight;
}

}


橘子类


public class Orange extends Fruit {
private double weight;

public Orange(double weight) {
this.weight = weight;
}

@Override
public double getWeight() {
return weight;
}

}


桃子类

public class Peach extends Fruit {
private double weight;

public Peach(double weight) {
this.weight = weight;
}

@Override
public double getWeight() {
return weight;
}
}


主类

public class Main {
public static void main(String[] args) {
// TODO Auto-generated method stub
Fruit[] fruits = { new Peach(12), new Apple(2), new Orange(5) };
for (Fruit fruit : fruits) {
System.out.println(fruit.getClass().getName() + "的重量是"
+ fruit.getWeight());
}
}
}

 

运行结果

Peach的重量是 12.0

Apple的重量是 2.0

Orange的重量是 5.0

温馨提示:答案为网友推荐,仅供参考
第1个回答  2017-06-16
abstract class Fruit {
    public Fruit() {
    }

    abstract float getWeight();

    @Override
    public String toString() {
        return "[name=" + this.getClass().getName() + ",weight=" + getWeight() + "]";
    }
}
class Apple extends Fruit{
    @Override
    float getWeight() {
        return 1;
    }
}
class Orange extends Fruit {
    @Override
    float getWeight() {
        return 2;
    }
}
public static void main(String[] args) {
        Fruit[] fruits = { new Apple(), new Orange() };
        for (Fruit fruit : fruits) {
            System.out.println(fruit.toString());
        }
    }

第2个回答  2015-10-09
//是这样吗?
public class Test {
public static void main(String[] args) {
Fruit[] fruits = new Fruit[6];
Apple apple1 = new Apple(2);
Peach peach2 = new Peach(1);
Tangerine tangerine3 = new Tangerine(3);
Apple apple4 = new Apple(4);
Peach peach5 = new Peach(6);
Tangerine tangerine6 = new Tangerine(5);
fruits[0] = apple1;
fruits[1] = peach2;
fruits[2] = tangerine3;
fruits[3] = apple4;
fruits[4] = peach5;
fruits[5] = tangerine6;
for(Fruit fruit : fruits) {
System.out.println(fruit.getClass().getName() + "," + fruit.getWeight());
}
}
}
abstract class Fruit {
int weight;
int getWeight() {
return weight;
}
}
class Apple extends Fruit{
public Apple(int weight) {
this.weight = weight;
}
}
class Peach extends Fruit{
public Peach(int weight) {
this.weight = weight;
}
}
class Tangerine extends Fruit{
public Tangerine(int weight) {
this.weight = weight;
}
}

本回答被网友采纳
相似回答