用Java定义一个名为Square的类的表示正方形,使其继承Shape抽象类,覆盖Shape类中的抽象方法get Perimeter()和get Area()。编写程序测试Squre类的使用
时间: 2024-03-17 13:41:01 浏览: 72
好的,以下是Square类的代码实现:
```java
abstract class Shape {
abstract double getPerimeter();
abstract double getArea();
}
class Square extends Shape {
private double side;
public Square(double side) {
this.side = side;
}
@Override
double getPerimeter() {
return 4 * side;
}
@Override
double getArea() {
return side * side;
}
}
```
为了测试Square类的使用,我们可以编写一个简单的程序:
```java
public class TestSquare {
public static void main(String[] args) {
Square square = new Square(5);
System.out.println("The perimeter of the square is " + square.getPerimeter());
System.out.println("The area of the square is " + square.getArea());
}
}
```
运行程序,输出如下:
```
The perimeter of the square is 20.0
The area of the square is 25.0
```
这说明Square类已经成功地继承了Shape抽象类,并且覆盖了其中的抽象方法。
阅读全文