定义Point类描述屏幕上的一个点。该类包括点的x和y两个坐标,及对点进行的相关操作,如:取得点的坐标值,对点的坐标进行赋值。此类属于MyPackageTwoD包。此包中另一个Rectangle类可以实现矩形的基本操作,包含Point、width、height等3个变量,及构造方法和其他方法。文件TestPackage.java中包含main()方法,
时间: 2024-01-24 17:17:38 浏览: 77
point类程序
可以使用Point和Rectangle类,创建对象并测试其功能。以下是Point类的示例代码:
```java
package MyPackageTwoD;
public class Point {
private int x;
private int y;
// 构造方法
public Point(int x, int y) {
this.x = x;
this.y = y;
}
// 获取x坐标
public int getX() {
return x;
}
// 获取y坐标
public int getY() {
return y;
}
// 设置x坐标
public void setX(int x) {
this.x = x;
}
// 设置y坐标
public void setY(int y) {
this.y = y;
}
}
```
以下是Rectangle类的示例代码:
```java
package MyPackageTwoD;
public class Rectangle {
private Point origin;
private int width;
private int height;
// 构造方法
public Rectangle(Point origin, int width, int height) {
this.origin = origin;
this.width = width;
this.height = height;
}
// 获取左上角的点
public Point getOrigin() {
return origin;
}
// 获取宽度
public int getWidth() {
return width;
}
// 获取高度
public int getHeight() {
return height;
}
// 设置左上角的点
public void setOrigin(Point origin) {
this.origin = origin;
}
// 设置宽度
public void setWidth(int width) {
this.width = width;
}
// 设置高度
public void setHeight(int height) {
this.height = height;
}
// 获取矩形面积
public int getArea() {
return width * height;
}
// 判断点是否在矩形内
public boolean contains(Point p) {
return p.getX() >= origin.getX() && p.getX() <= origin.getX() + width
&& p.getY() >= origin.getY() && p.getY() <= origin.getY() + height;
}
}
```
以下是TestPackage.java的示例代码:
```java
package MyPackageTwoD;
public class TestPackage {
public static void main(String[] args) {
// 创建一个点对象
Point p1 = new Point(2, 3);
System.out.println("Point p1: (" + p1.getX() + ", " + p1.getY() + ")");
// 改变点的坐标
p1.setX(5);
p1.setY(7);
System.out.println("Point p1: (" + p1.getX() + ", " + p1.getY() + ")");
// 创建一个矩形对象
Rectangle rect = new Rectangle(new Point(1, 2), 5, 4);
System.out.println("Rectangle origin: (" + rect.getOrigin().getX() + ", " + rect.getOrigin().getY() + ")");
System.out.println("Rectangle width: " + rect.getWidth());
System.out.println("Rectangle height: " + rect.getHeight());
System.out.println("Rectangle area: " + rect.getArea());
// 判断一个点是否在矩形内
Point p2 = new Point(3, 4);
System.out.println("Point p2 is inside the rectangle: " + rect.contains(p2));
Point p3 = new Point(6, 5);
System.out.println("Point p3 is inside the rectangle: " + rect.contains(p3));
}
}
```
运行TestPackage.java,输出如下:
```
Point p1: (2, 3)
Point p1: (5, 7)
Rectangle origin: (1, 2)
Rectangle width: 5
Rectangle height: 4
Rectangle area: 20
Point p2 is inside the rectangle: true
Point p3 is inside the rectangle: false
```
阅读全文