高级内存
对象与对象
对象作为方法传参
Point.java
1 2 3 4 5 6 7 public class Point { ... public boolean onRight(Point target) { return target.x > this.x; } ...}
Driver.java
1 2 3 4 5 6 7 8 9 10 11 12 public class Driver { ... public static void main(String[] args) { Point p1 = new Point(1, 2); Point p2 = new Point(3, 4); boolean result = p1.onRight(p2); System.out.println(result); } ...}
对象作为方法返回值
Point.java
1 2 3 4 5 6 7 public class Point { ... public Point flippedPoint() { return new Point(-y, -x); } ...}
Driver.java
1 2 3 4 5 6 7 8 9 10 11 public class Driver { ... public static void main(String[] args) { Point p1 = new Point(1, 2); Point p2 = p1.flippedPoint(); System.out.println(p2); } ...}
对象作为属性
Rect.java
1 2 3 4 5 6 7 8 9 10 11 public class Rect { private Point origin; private int width; private int height; public int maxY() { return origin.getX() + width; } ...}
Driver.java
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 public class Driver { ... public static void main(String[] args) { Point p1 = new Point(1, 2); Rect rect = new Rect(); rect.setPoint(p1); rect.setWidth(3); rect.setHeight(6); int right = rect.maxY(); System.out.println(right); } ...}