Why Private Property Rather Than Public Property In Java?
来源:互联网 发布:箱体捉妖指标公式源码 编辑:程序博客网 时间:2024/06/17 13:14
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
- Why Private Property Rather Than Public Property In Java?
- thinking in java 之 public private protect
- public、protected、private in c++ and java
- private, default, protected, public in Java
- Why use API's rather than system calls?
- Why do we use int rather than char
- Why should we copy blocks rather than retain?
- Public Property angle() As Single
- property
- property
- Property
- @property
- @property
- property
- @property(..,..)
- property
- @property
- property
- 数据结构课程设计——考试报名管理系统
- To Me
- Semi-direct Visual Odometry(SVO)安装配置
- 走进AngularJs(七) 过滤器(filter) - 吕大豹
- JavaScript也有设计模式(一)——简单工厂模式
- Why Private Property Rather Than Public Property In Java?
- 设置a的bit 3
- PHP中$GLOBALS与global的区别
- 学习、工作心得分享
- 39,40,216 Combination Sum I II III
- ServletContext详解
- MYSQL经典SQL之生日问题
- 开源框架01(ion,Volley,retrofit;Glide,picasso,fresco)
- PAT-1009B 说反话 (20)