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

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

水果类

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

很简单啊,把苹果当成一个数组或者集合,然后遍历集合,在遍历的段陆穗过程中,做if判断握卜悉携,判断大小的零界点来把苹果分类。

int[] args={1,2,3,4,5,6,7,8,9}

List da=new ArrayList()

List xiao=new ArrayList()

for(int i=0i<args.lengthi++){

if(args[i]>5){

da.add(args[i])

}else{

xiao.add(args[i])

}

}

类似这种把数组分大小


欢迎分享,转载请注明来源:内存溢出

原文地址: http://outofmemory.cn/yw/12429487.html

(0)
打赏 微信扫一扫 微信扫一扫 支付宝扫一扫 支付宝扫一扫
上一篇 2023-05-25
下一篇 2023-05-25

发表评论

登录后才能评论

评论列表(0条)

保存