类的组合
组合的语法
package com.study.classReuse.compositionOfClasses;
// 类的组合举例
class Point{ // 表示一个点的类
private int x, y; // 一个点有两个坐标
// 构造方法
public Point(int x, int y) {
this.x = x;
this.y = y;
}
public int getX() {
return x;
}
public int getY() {
return y;
}
}
class Line { // 表示一条线的类
private Point p1, p2; // 定义引用变量,线段有两个端点p1,p2
//构造方法
Line(Point a, Point b) { // 传入两个点对象
p1 = new Point(a.getX(), a.getY());
// 为什么不用p1=a?如果直接写成p1=a,则p1和外部传入的a会指向同一个Point对象,此时若外部代码修改了a,则p1坐标会被改变
p2 = new Point(b.getX(), b.getY());
// 同理
}
double Length(){
return Math.sqrt(Math.pow(p2.getX() - p1.getX(), 2) + Math.pow(p2.getY() - p1.getY(), 2));
}
}
public class LineTester{
public static void main(String[] args) {
Point p1 = new Point(1, 1);
Point p2 = new Point(2, 2);
Line l1 = new Line(p1, p2);
Line l2 = new Line(new Point(1,2), new Point(2, 1));
System.out.println("线段l1的长度为" + l1.Length());
System.out.println("线段l2的长度为" + l2.Length());
}
}
线段l1的长度为1.4142135623730951
线段l2的长度为1.4142135623730951

被折叠的 条评论
为什么被折叠?



