java无忧网

标题: 定义一个水果类。其中包括getweight()方法,编写程序分别创建苹果、香蕉、橙子3个对象 [打印本页]

作者: java无忧网    时间: 2020-4-9 16:13
标题: 定义一个水果类。其中包括getweight()方法,编写程序分别创建苹果、香蕉、橙子3个对象
定义一个水果类。其中包括getweight()方法,编写程序分别创建苹果、香蕉、橙子3个对象,水果对象存放在一个水果类型的数组中 ,输出数组中所有水果的类型、重量。提示,用getClass().getName方法可以获取对象所属的类的名称。


public class Main {
    public static void main(String[] args) {
        // TODO Auto-generated method stub
            //定义 数组
        Fruit[] fruits = { new Banana(15), new Apple(7), new Orange(5) };
        //循环数组
        for (Fruit fruit : fruits) {
                //获取对象名称
                Class c=fruit.getClass();
                System.out.println(c.getName());
                //输出水果重量
            System.out.println("重量是:"+ fruit.getWeight());
        }
    }
}


/**
* 水果抽象类
*/
abstract  class Fruit {
        //获取重量
    abstract public double getWeight();
}


/**
* 橙子类
*/
class Orange extends Fruit {
    private double weight;//定义 重量

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

    //重写体重方法
    public double getWeight() {
        return weight;
    }

}


/**
*
*香蕉类
*
*/
class Banana extends Fruit {
    private double weight;//定义 重量
     
    public Banana(double weight) {
        this.weight = weight;
    }

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


/**
* 苹果
*/
class Apple extends Fruit {
    private double weight;//定义 重量

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

//重写体重方法
    public double getWeight() {
        return weight;
    }

}






欢迎光临 java无忧网 (http://www.javawyw.com/) Powered by Discuz! X3.2