黑马程序员技术交流社区

标题: 数据域封装的问题 [打印本页]

作者: 二月的雨    时间: 2014-12-8 16:39
标题: 数据域封装的问题
有下面一个很基本的代码,提问是:为什么第一,二次的显示结果是一样的呢?
源代码如下:
public class TestCircle3
{
public static void main(String[] args)
{
  Circle3 myCircle = new Circle3(5.0);
  System.out.println("The area of the radius "+myCircle.getRadius()+" is "+myCircle.getArea());
  
  myCircle.setRadius(myCircle.getRadius() * 1.1);
  System.out.println("The area of the radius "+myCircle.getRadius()+" is "+myCircle.getArea());
  
  System.out.println("The number of objects creased is "+Circle3.getNumberOfObjects());
}
}
class Circle3
{
private double radius = 1.0;

private static int numberOfObjects;

public Circle3()
{
  numberOfObjects++;
}

public Circle3(double newRadius)
{
  radius = newRadius;
  numberOfObjects++;
}

public double getRadius()
{
  return radius;
}

public void setRadius(double newRadius)
{
  radius = (newRadius > 0) ? radius : 0;
}

public static int getNumberOfObjects()
{
  return numberOfObjects;
}

public double getArea()
{
  return radius * radius * Math.PI;
}
}

运行结果如下:
The area of the radius 5.0 is 78.53981633974483
The area of the radius 5.0 is 78.53981633974483
The number of objects creased is 1






欢迎光临 黑马程序员技术交流社区 (http://bbs.itheima.com/) 黑马程序员IT技术论坛 X3.2