1. 创建一个Shape父类, a) 该类有一个Point的类型的私有属性center,表示shape的中心点坐标 b) 二个成员方法:double getArea()获取图形的面积,默认返回值为0,double getPerimeter() 获取图形的周长,默认返回值为0
时间: 2024-02-03 13:11:25 浏览: 28
好的,您的第一个问题是如何创建一个Shape父类。根据您的要求,可以创建一个Shape类如下:
```
class Shape {
private Point center;
public Shape(Point center) {
this.center = center;
}
public double getArea() {
return 0;
}
public double getPerimeter() {
return 0;
}
}
```
这个Shape类有一个Point类型的私有属性center,表示shape的中心点坐标。此外,它也有两个成员方法:getArea()获取图形的面积,默认返回值为0,getPerimeter()获取图形的周长,默认返回值为0。请问,您是否还有其他问题需要我的帮助呢?
相关问题
2 求面积 (1) 创建一个抽象父类shape,具有抽象方法getarea(),用于求此形状的面积
(2) 创建两个子类:rectangle(矩形)和circle(圆形),继承父类shape。
(3) 子类rectangle和circle分别实现getarea()方法,以计算矩形和圆形的面积。
(4) 在主函数中,创建矩形和圆形的对象,并调用各自的getarea()方法,得到面积。
(5) 最后将计算的面积输出。
下面是代码示例:
```python
import math
# 父类shape
class Shape:
def getarea(self):
pass
# 子类rectangle
class Rectangle(Shape):
def __init__(self, width, height):
self.width = width
self.height = height
def getarea(self):
return self.width * self.height
# 子类circle
class Circle(Shape):
def __init__(self, radius):
self.radius = radius
def getarea(self):
return math.pi * self.radius**2
# 主函数
def main():
# 创建矩形对象
rect = Rectangle(3, 4)
# 调用getarea()方法求面积
rect_area = rect.getarea()
print("矩形的面积为:", rect_area)
# 创建圆形对象
cir = Circle(5)
# 调用getarea()方法求面积
cir_area = cir.getarea()
print("圆形的面积为:", cir_area)
# 调用主函数
main()
```
运行结果:
矩形的面积为: 12
圆形的面积为: 78.53981633974483
创建一个shape公共类,该类具有length和height两个属性,具有带参数和不带参数的构
造函数,并且具有计算面积的方法。你可以这样实现:
```python
class Shape:
def __init__(self, length=0, height=0):
self.length = length
self.height = height
def area(self):
return self.length * self.height
```
这个公共类中有两个属性,分别是`length`和`height`,默认值为0。在构造函数中,我们将这两个属性初始化为传入的值。此外,我们还定义了一个`area`方法,用来计算长方形的面积,即`length * height`。