用java编程序:现有一套木质七巧板需要用赤、橙、黄、绿、青、蓝、紫 7 种颜色进行油漆,七块板拼 成的正方形边长为 10 米,厚度为 1 米,颜色分布如图 4.4 所示。每平方米面积使用油漆一 小桶,编写程序计算出油漆一套七巧板需用 7 种油漆各多少桶。 要求:程序中需运用到继承与多态的概念
时间: 2024-03-14 08:47:21 浏览: 121
java源码:java俄罗斯方块.zip
以下是一个使用继承与多态概念的Java程序,用于计算油漆一套七巧板需要用7种油漆各多少桶:
```java
public abstract class SevenPieces {
protected int boardNum; // 板子数量
protected int boardArea; // 每块板子面积
protected int boardThickness; // 板子厚度
protected int squareSideLength; // 正方形边长
public SevenPieces(int boardNum, int boardArea, int boardThickness, int squareSideLength) {
this.boardNum = boardNum;
this.boardArea = boardArea;
this.boardThickness = boardThickness;
this.squareSideLength = squareSideLength;
}
public abstract int getPaintBucketNum(); // 抽象方法,用于计算油漆桶数量
}
public class RedPiece extends SevenPieces {
public RedPiece(int boardNum, int boardArea, int boardThickness, int squareSideLength) {
super(boardNum, boardArea, boardThickness, squareSideLength);
}
@Override
public int getPaintBucketNum() {
int totalArea = boardNum * squareSideLength * squareSideLength;
return totalArea / boardArea;
}
}
public class OrangePiece extends SevenPieces {
public OrangePiece(int boardNum, int boardArea, int boardThickness, int squareSideLength) {
super(boardNum, boardArea, boardThickness, squareSideLength);
}
@Override
public int getPaintBucketNum() {
int totalArea = boardNum * squareSideLength * squareSideLength;
return totalArea / boardArea;
}
}
// 同理实现 YellowPiece、GreenPiece、CyanPiece、BluePiece、PurplePiece 类
public class PaintCalculator {
public static void main(String[] args) {
// 创建七巧板对象
SevenPieces[] pieces = new SevenPieces[7];
pieces[0] = new RedPiece(1, 10, 1, 10);
pieces[1] = new OrangePiece(1, 10, 1, 10);
pieces[2] = new YellowPiece(2, 10, 1, 10);
pieces[3] = new GreenPiece(2, 10, 1, 10);
pieces[4] = new CyanPiece(1, 10, 1, 10);
pieces[5] = new BluePiece(1, 10, 1, 10);
pieces[6] = new PurplePiece(1, 10, 1, 10);
// 输出结果
System.out.println("油漆一套七巧板需要用以下油漆桶数量:");
System.out.println("赤:" + pieces[0].getPaintBucketNum());
System.out.println("橙:" + pieces[1].getPaintBucketNum());
System.out.println("黄:" + pieces[2].getPaintBucketNum());
System.out.println("绿:" + pieces[3].getPaintBucketNum());
System.out.println("青:" + pieces[4].getPaintBucketNum());
System.out.println("蓝:" + pieces[5].getPaintBucketNum());
System.out.println("紫:" + pieces[6].getPaintBucketNum());
}
}
```
在这个程序中,我们定义了一个抽象类 SevenPieces,包含了七巧板的基本属性和一个抽象方法 getPaintBucketNum()。然后,我们分别定义了七种颜色的七巧板类 RedPiece、OrangePiece、YellowPiece、GreenPiece、CyanPiece、BluePiece、PurplePiece,这些类继承了 SevenPieces 类并实现了它的抽象方法。在程序的主函数中,我们创建了七巧板对象,并分别调用它们的 getPaintBucketNum() 方法来计算需要多少桶油漆。由于每个类实现了 SevenPieces 中的抽象方法,所以我们可以通过 SevenPieces 类型的数组来保存这些对象,并通过多态的方式来调用它们的方法。这种设计方式使得程序更加灵活,易于扩展。
阅读全文