酷代码 AI
菜单
服务商

java实现原型模式 二维空间的圆circle具有原点p和半径r,原点p是point类型,point类具有x,y两个属性,代表点的坐标,对圆进行浅克隆

以下是使用 Java 实现原型模式对二维空间的圆 `Circle` 进行浅克隆的示例代码: ```java class Point { int x; int y; Point(int x, int y) { this.x = x; this.y = y; } // 重写 clone 方法进行浅克隆 @Override protected Point clone() { try { return (Point) super.clone(); } catch (CloneNotSupportedException e) { throw new RuntimeException(e); } } } class Circle implements Cloneable { Point p; int r; Circle(Point p, int r) { this.p = p; this.r = r; } // 重写 clone 方法进行浅克隆 @Override protected Circle clone() { try { Circle clone = (Circle) super.clone(); // 浅克隆,只复制对象的引用 clone.p = this.p.clone(); return clone; } catch (CloneNotSupportedException e) { throw new RuntimeException(e); } } public static void main(String[] args) { Point p1 = new Point(10, 20); Circle c1 = new Circle(p1, 5); // 进行浅克隆 Circle c2 = c1.clone(); // 修改原始对象的属性 c1.p.x = 30; // 打印克隆对象的属性 System.out.println("克隆对象 c2 的原点坐标: " + c2.p.x + ", " + c2.p.y); } } ``` 在上述代码中,`Point` 类和 `Circle` 类都实现了 `clone` 方法来支持浅克隆。在 `Circle` 的 `clone` 方法中,对内部的 `Point` 对象也进行了克隆操作。 [2024-11-07 16:26:29 | AI写代码神器 | 442点数解答]

相关提问
实用工具查看更多
今日油价 [生活类]
图片互转base64 [开发类]
时间转换器 [开发类]
数独游戏 [娱乐类]
经典推箱子 [娱乐类]
AI摸鱼五子棋 [娱乐类]