JavaSE系列代码06: 定义私有成员,使之无法在类外被访问

  1. As a member of an external class, an internal class can access private members or properties of the external class. (even if the outer class is declared private, it is visible to the inner class that is inside.)
  2. Use inner class to define properties that are not accessible in outer class. In this way, the access rights in the external class are smaller than that in the private of the external class.
    Note: inner class is a compile time concept. Once compiled successfully, it will become two completely different classes.
    For an external class named outer and an internal class named inner defined within it. After the compilation, there are two types: outer. Class and outer $inner. Class.
  3. A member internal class cannot define static members, only object members.
class Cylinder    //定义Cylinder类
{
  private double radius;   //将数据成员radius声明为私有的
  private int height;      //将数据成员height声明为私有的
  private double pi=3.14;  //将数据成员pi声明为私有的,并赋初值
  double area()
  {
    return pi* radius* radius;  //在Cylinder类内部,故可访问私有成员
  }
  double volume()
  {
    return area()*height;      //在类内可以访问私有成员height
  }
}
public class Javase_06       //定义公共主类
{
  public static void main(String[] args)
  {
    Cylinder volu;
    volu=new Cylinder();
    volu.radius=2.8; 
    volu.height=-5;
    System.out.println("底圆半径="+volu.radius);
    System.out.println("圆柱的高="+volu.height);
    System.out.print("圆柱");
    System.out.println("底面积="+volu.area());
    System.out.println("圆柱体体积="+volu.volume());
  }
}

发布了13 篇原创文章 · 获赞 160 · 访问量 8543

猜你喜欢

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