用java语言 设计一个能细分为矩形、角形、肉形和椭圆彦的“图形”类。使用继承将这要图形分类,找出能作为基关部分的共同特征(如换准点)和方法(如画法、初始化)。并看看这些图形是否能进一步划分为子类。
时间: 2024-10-18 22:05:14 浏览: 17
在Java中设计这样一个"图形"类及其子类,可以采用继承和封装的原则,首先创建一个名为`Shape`的基类,包含一些通用的属性(例如位置x和y坐标)和方法(如`draw()`用于绘制图形)。然后,我们可以创建四个具体的形状类,如`Rectangle`, `Circle`, `Triangle`, 和 `Ellipse`,它们都从`Shape`类继承。
```java
// 基类 Shape
public abstract class Shape {
protected double x;
protected double y;
public Shape(double x, double y) {
this.x = x;
this.y = y;
}
// 共享的方法
public void draw() {
System.out.println("Drawing a generic shape at (" + x + ", " + y + ")");
}
// 公共属性,例如变换中心点
public double getX() {
return x;
}
public double getY() {
return y;
}
public void setX(double newX) {
x = newX;
}
public void setY(double newY) {
y = newY;
}
}
// 子类 Rectangle
public class Rectangle extends Shape {
private double width;
private double height;
public Rectangle(double x, double y, double width, double height) {
super(x, y);
this.width = width;
this.height = height;
}
// 重写 draw() 方法
@Override
public void draw() {
System.out.println("Drawing a rectangle at (" + x + ", " + y + ") with size " + width + "x" + height);
}
}
// 子类 Circle
public class Circle extends Shape {
private double radius;
public Circle(double x, double y, double radius) {
super(x, y);
this.radius = radius;
}
// 重写 draw() 方法
@Override
public void draw() {
System.out.println("Drawing a circle at (" + x + ", " + y + ") with radius " + radius);
}
}
// 子类 Triangle
public class Triangle extends Shape {
private double sideA;
private double sideB;
private double sideC;
public Triangle(double x, double y, double sideA, double sideB, double sideC) {
super(x, y);
this.sideA = sideA;
this.sideB = sideB;
this.sideC = sideC;
}
// 重写 draw() 方法
@Override
public void draw() {
System.out.println("Drawing a triangle at (" + x + ", " + y + ") with sides " + sideA + ", " + sideB + ", and " + sideC);
}
}
// 子类 Ellipse
public class Ellipse extends Shape {
private double majorAxis;
private double minorAxis;
public Ellipse(double x, double y, double majorAxis, double minorAxis) {
super(x, y);
this.majorAxis = majorAxis;
this.minorAxis = minorAxis;
}
// 重写 draw() 方法
@Override
public void draw() {
System.out.println("Drawing an ellipse at (" + x + ", " + y + ") with major axis " + majorAxis + " and minor axis " + minorAxis);
}
}
阅读全文