JavaSE系列代码07: 定义公共方法来访问私有成员

Data is the result of fact or observation, the logical induction of objective things, and the raw material used to express objective things.
Data can be continuous values, such as sound and image, called analog data. Also can be discrete, such as symbols, text, called digital data.
In a computer system, data is represented as binary information unit 0,1.

class Cylinder
{
  private double radius;  //声明私有数据成员
  private int height; 
  private double pi=3.14;
  public void SetCylinder(double r, int h)  //声明具有2个参数的公共方法
  {                                 //用于对私有数据进行访问
    if (r>0&& h>0)
    {
      radius=r;
      height=h;
    }
    else
      System.out.println("您的数据有错误!!");
  }
  double area()
  {
    return pi* radius* radius;     //在类内可以访问私有成员radius和pi
  }
  double volume()
  {
    return area()*height;        //在类内可以访问私有成员height
  }
}
public class Javase_07   //定义公共主类
{
  public static void main(String[] args)
  {
    Cylinder volu=new Cylinder();
    volu.SetCylinder(2.5, -5);     //通过公共方法SetCylinder()访问私有数据
    System.out.println("圆柱底面积="+volu.area());
    System.out.println("圆柱体体积="+volu.volume());
  }
}
发布了13 篇原创文章 · 获赞 160 · 访问量 8542

猜你喜欢

转载自blog.csdn.net/blog_programb/article/details/105376974