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

已举报 回答
java程序题:定义一个抽象类-水果,其中包含getWeight()方法,编写程序分别创建苹果、
问在线客服
扫码问在线客服
  • 回答数

    3

  • 浏览数

    6,368

3个回答 默认排序
  • 默认排序
  • 按时间排序

已采纳
水果类
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
取消 评论
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()); } }
取消 评论
//是这样吗?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; }}
取消 评论
ZOL问答 > java程序题:定义一个抽象类-水果,其中包含getWeight()方法,编写程序分别创建苹果、

举报

感谢您为社区的和谐贡献力量请选择举报类型

举报成功

经过核实后将会做出处理
感谢您为社区和谐做出贡献

扫码参与新品0元试用
晒单、顶楼豪礼等你拿

扫一扫,关注我们
提示

确定要取消此次报名,退出该活动?