1.封装思想:将对象的属性和行为封装起来的载体是类,类通常对客户隐藏其实现的细节

2.封装就是将属性私有化(private),并提供公共的方法(public)访问私有属性

3.通过封装,实现对属性数据的访问限制,提高程序可维护性

 1 public class enca {
 2     private int i;
 3     private String str;  //私有属性
 4     public int getI() {//提供公共方法访问私有属性
 5         return i;
 6     }
 7     public void setI(int i) {
 8         this.i = i;
 9     }    
10     public String getStr() {
11         return str;
12     }
13     public void setStr(String str) {
14         this.str = str;
15     }
16 }

可见,实现封装的步骤:

1.将属性私有化,限制外部方法对属性的访问

2.为每个属性创建赋值方法和取值方法,即set和get,用于对这些属性的访问

 

相关文章:

  • 2022-12-23
  • 2022-12-23
  • 2021-07-27
  • 2022-01-26
  • 2021-08-17
  • 2022-01-21
  • 2021-12-23
  • 2021-11-03
猜你喜欢
  • 2021-10-08
  • 2021-05-18
  • 2021-10-12
  • 2021-07-03
  • 2021-09-16
  • 2021-10-13
  • 2021-08-30
相关资源
相似解决方案