用java语言代码编写 设计一个能细分为矩形、角形、肉形和椭圆彦的“图形”类。使用继承将这要图形分类,找出能作为基关部分的共同特征(如换准点)和方法(如画法、初始化)。并看看这些图形是否能进一步划分为子类。 本题只考虑实现思想,不者虑具体实现的细育,更现方式可自由发择。
时间: 2024-10-10 14:14:25 浏览: 24
jwap-1.1-src.zip_WAP Gateway Java_gateway_jwap_jwap source code_
为了设计这个图形类以及其子类,我们可以创建一个名为`Shape`的基类,它包含一些通用的属性和方法,然后让矩形、角形、肉形和椭圆分别继承自`Shape`。共享的特征比如位置和绘制方法可以放在基类中,而每个形状特有的属性(如长宽、角度等)则由子类实现。以下是简化的代码结构:
```java
// 基类 Shape
public abstract class Shape {
protected Point location; // 共享的位置属性
public Shape(Point location) {
this.location = location;
}
// 公共方法
public abstract void draw();
// 共享的变换方法
public void setLocation(Point newLocation) {
location = newLocation;
}
}
// 子类 Rectangle
public class Rectangle extends Shape {
private double width, height;
public Rectangle(Point location, double width, double height) {
super(location);
this.width = width;
this.height = height;
}
@Override
public void draw() {
System.out.println("Drawing rectangle at (" + location.getX() + ", " + location.getY() + ")");
}
}
// 子类 Pentagon (假设是一个五边形)
public class Pentagon extends Shape {
private double sideLength;
public Pentagon(Point location, double sideLength) {
super(location);
this.sideLength = sideLength;
}
@Override
public void draw() {
System.out.println("Drawing pentagon at (" + location.getX() + ", " + location.getY() + ")");
}
}
// 子类 Blob (肉形,这里简单假设它有一个半径)
public class Blob extends Shape {
private double radius;
public Blob(Point location, double radius) {
super(location);
this.radius = radius;
}
@Override
public void draw() {
System.out.println("Drawing blob at (" + location.getX() + ", " + location.getY() + ")");
}
}
// 子类 Ellipse
public class Ellipse extends Shape {
private double xRadius, yRadius;
public Ellipse(Point location, double xRadius, double yRadius) {
super(location);
this.xRadius = xRadius;
this.yRadius = yRadius;
}
@Override
public void draw() {
System.out.println("Drawing ellipse at (" + location.getX() + ", " + location.getY() + ")");
}
}
```
在这个例子中,`Shape`类代表了所有图形的共通特性,而每个子类都添加了各自特有的属性和方法。如果需要进一步细分,可以根据实际需求为每个形状创建更多的子类。
阅读全文