Why Private Property Rather Than Public Property In Java?

Why To Set A Property To Be Private Rather Than To Be Public Directly In Java?

You will use like this:

class Door{
    private double width;
    private double height;

    public setWidth(double width){
        this.width = width;
    }
    public getWidth(){
         return width;
    }
    public setHeight(double height){
        this.height = height;
    }
    public getHeight(){
         return height;
    }
}

You won’t use like this:

class Door{
    public double width;
    public double height;
}

WHY?–>Principle: Package

I’ll show this to you in three case:

  • The first:
    You must make the property of width be private and get it by method getWidth() when the width of the door can be get only but can not be set.
class Door{
    private double width;
    private double height;

    //public setWidth(double width){
    //    this.width = width;
    //}

    public getWidth(){
         return width;
    }

    public setHeight(double height){
        this.height = height;
    }
    public getHeight(){
         return height;
    }
}
  • The second:
    You must make the property of width be private and set it by method setWidth() when the width of the door is limited.
    public setWidth(double width){
        if(width <= 10){    //width[10, 210]
            width = 10;
        } else if(width >= 120){
            width = 120;
        } else {
            this.width = width;        
        }
    }

    Door myDoor = new Door();
    myDoor.setWidth(-12);
    myDoor.setWidth(132);
    myDoor.setWidth(98);
  • The three:
    You can change it by extending the class easily if the size of the width must change.

这里写图片描述

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值