组合与复用
·Circle类创建圆对象
·Circle类创建圆锥对象,Circle类将Circle类声明的对象作为自己的一个成员
·圆锥通过调用方法将某个圆的引用传递给圆锥的Circle类型的成员变量
package Absent; public class Chapter3 { public static void main(String[] args) { // TODO Auto-generated method stub Circle circle=new Circle(); circle.setRadius(10); Circular circular=new Circular(); System.out.println("circle的引用:"+circle); System.out.println("圆锥的bottom引用:"+circular.bottom); circular.setHeight(5); circular.setBottom(circle); System.out.println("circle的引用:"+circle); System.out.println("圆锥的Bottom引用:"+circular.bottom); System.out.println("圆锥的体积:"+circular.getBottomRadius()); System.out.println("修改circle的半径,bottom的半径同样发生变化。"); circle.setRadius(20); System.out.println("bottom的半径"+circular.getBottomRadius()); System.out.println("重新创建circle,circle的引用将会发生变化"); circle=new Circle();//重新创建circle System.out.println("circle的引用:"+circle); System.out.println("但不影响circular的bottom引用"+circular.bottom); } } class Circle{ double radius,area; void setRadius(double r) { radius=r; } double getRadius() { return radius; } double getArea() { return area=3.14*radius*radius; } } class Circular{ Circle bottom; double height; void setBottom(Circle c) { bottom=c; } void setHeight(double h) { height=h; } double getVolume() { if(bottom==null) return -1; else return bottom.getArea()*height/3.0; } double getBottomRadius() { return bottom.getRadius(); } public void setBottomRadius(double r) { bottom.setRadius(r); } }