两种方法说明

  对于一个类中的成员变量(属性),如果都被设置成了private私有数据类型,则对外给属性设置了get和set方法 ,
  
  外部程序中给这些属性设置值,有两种方式.
   1.通过set()方法.
   2.通过含有这个属性的构造方法来直接设置这个属性的值.

   构造函数就是在实例化这个类的时候给属性赋值.
   set是在实例化时没有赋值或者改变值的时候用,get是调用类中属性的时候用

程序举例

package java1;

public class Fan {
        int SLOW = 1;
        int MEDIUM = 2;
        int FAST = 3;
        int speed = SLOW;
        boolean on = false;
        double radius = 5;
        String color = "blue";
        int getSpeed() {
            return speed;
        }
        boolean getOn() {
            return on;
        }
        double getRadius() {
            return radius;
        }
        String getColor() {
            return color;
        }
        //set()设置值方法  
        public void setOn(boolean on) {
            this.on = on;
        }
        public void setRadius(double radius) {
            this.radius = radius;
        }
         public void setSpeed(int speed) {
            this.speed = speed;
        }
        public void setColor(String color) {
            this.color = color;
        }
        public Fan() {
        }
        //构造方法赋值
        public Fan(int speed,double radius,String color,boolean on) {
            this.speed = speed;
            this.radius = radius;
            this.color = color;
            this.on = on;
        }

        //toString方法返回字符串描述
         public String toString() {
             if(on==true){
                    return "该风扇的速度为:" + speed +";颜色是:"+color+";半径是:"+radius;
             }      
             else{
                    return "fan is off;"+"该风扇的颜色是:"+color+";半径是:"+radius;
             }
         }

    public static void main(String[] args) {
            Fan fan1 = new Fan(3,10,"yellow",true);
            Fan fan2 = new Fan(2,5,"blue",false);
            System.out.println(fan1.toString());
            System.out.println(fan2.toString());
    }
}