5. 创建一个Shape类(形状),属性int x(x坐标), int y(y坐标),定义有参无参,set/get/toString方法 创建一个Square类(方形)继承Shape类,定义有参无参,set/get/toString方法 创建一个Triangle类(三角形)继承Shape类,定义有参无参,set/get/toString方法 在main方法中创建4个Square对象,将四个点连起来是一个正方形,输出这4个点 在main方法中创建3个Triangle对象,将三个点连起来是一个等腰三角形,输出这个3个点
时间: 2024-03-06 07:46:12 浏览: 82
好的,我知道了。以下是代码实现:
```java
// Shape类
public class Shape {
private int x;
private int y;
public Shape() {
}
public Shape(int x, int y) {
this.x = x;
this.y = y;
}
public int getX() {
return x;
}
public void setX(int x) {
this.x = x;
}
public int getY() {
return y;
}
public void setY(int y) {
this.y = y;
}
@Override
public String toString() {
return "(" + x + ", " + y + ")";
}
}
// Square类
public class Square extends Shape {
public Square() {
}
public Square(int x, int y) {
super(x, y);
}
@Override
public String toString() {
return "Square{" +
"x1=" + getX() +
", y1=" + getY() +
", x2=" + (getX() + 1) +
", y2=" + getY() +
", x3=" + (getX() + 1) +
", y3=" + (getY() + 1) +
", x4=" + getX() +
", y4=" + (getY() + 1) +
'}';
}
}
// Triangle类
public class Triangle extends Shape {
public Triangle() {
}
public Triangle(int x, int y) {
super(x, y);
}
@Override
public String toString() {
return "Triangle{" +
"x1=" + getX() +
", y1=" + getY() +
", x2=" + (getX() + 1) +
", y2=" + getY() +
", x3=" + getX() +
", y3=" + (getY() + 1) +
'}';
}
}
// main方法
public static void main(String[] args) {
// 创建4个Square对象
Square square1 = new Square(0, 0);
Square square2 = new Square(1, 0);
Square square3 = new Square(1, 1);
Square square4 = new Square(0, 1);
// 输出这4个点
System.out.println(square1);
System.out.println(square2);
System.out.println(square3);
System.out.println(square4);
// 创建3个Triangle对象
Triangle triangle1 = new Triangle(0, 0);
Triangle triangle2 = new Triangle(1, 0);
Triangle triangle3 = new Triangle(0, 1);
// 输出这3个点
System.out.println(triangle1);
System.out.println(triangle2);
System.out.println(triangle3);
}
```
输出结果如下:
```
Square{x1=0, y1=0, x2=1, y2=0, x3=1, y3=1, x4=0, y4=1}
Square{x1=1, y1=0, x2=2, y2=0, x3=2, y3=1, x4=1, y4=1}
Square{x1=1, y1=1, x2=2, y2=1, x3=2, y3=2, x4=1, y4=2}
Square{x1=0, y1=1, x2=1, y2=1, x3=1, y3=2, x4=0, y4=2}
Triangle{x1=0, y1=0, x2=1, y2=0, x3=0, y3=1}
Triangle{x1=1, y1=0, x2=2, y2=0, x3=1, y3=1}
Triangle{x1=0, y1=1, x2=1, y2=1, x3=0, y3=2}
```
阅读全文