将属性定义为static(静态),然后在构造器里自动复制
例:
public class CircleTest {
public static void main(String[] args) {
Circle c1=new Circle();
Circle c2=new Circle();
Circle c3=new Circle(3.4);
System.out.println("c1的id:"+c1.getId());
System.out.println("c2的id:"+c2.getId());
System.out.println("c3的id:"+c3.getId());
System.out.println("创建的圆的个数:"+Circle.getTotal());
}
}
class Circle{
private double radius;
private int id;//自动赋值
public Circle(){
id=init++;
total++;
}
public Circle(double radius) {
this();
this.radius=radius;
// id=init++;
// total++;
}
private static int init=1001;
private static int total;
public double findArea() {
double area=3.14*radius*radius;
return area;
}
public double getRadius() {
return radius;
}
public void setRadius(double radius) {
this.radius = radius;
}
public int getId() {
return id;
}
public static int getTotal() {
return total;
}
}
欢迎分享,转载请注明来源:内存溢出
评论列表(0条)