封装详解

 

 

 1 package com.oop.demo4;
 2 //类     private: 私有
 3 public class Student {
 4     //属性私有
 5     private String name; //名字
 6     private int id; //学号
 7     private char sex; //性别
 8     private int age;//年龄
 9 
10     // 提供一些可以操作这个属性的方法!
11     // 提供--些public 的get. set方法
12     //get获得这个数据
13     public String getName(){
14         return this. name ;
15     }
16     //set给这个数据设置值
17     public void setName(String name){
18         this.name = name;
19     }
20 
21     //alt+insert
22 
23     public int getId() {
24         return id;
25     }
26 
27     public void setId(int id) {
28         this.id = id;
29     }
30 
31     public char getSex() {
32         return sex;
33     }
34 
35     public void setSex(char sex) {
36         this.sex = sex;
37     }
38 
39     public int getAge() {
40         return age;
41     }
42 
43     public void setAge(int age) {
44         if (age>120 || age<0){ //不合法
45             this.age = 3;
46         }else {
47             this.age = age;
48         }
49 
50     }
51 }
52 /*
53     1.提高程序的安全性,保护数据
54     2.隐藏代码的实现细节
55     3.统一接口
56     4.系统可维护增加了
57 public class Application {
58     public static void main(String[] args) {
59         Student s1 = new Student( );
60         s1. setName("小明 ");
61         System. out. println(s1.getName());
62 
63         s1.setAge(999);//不合法
64         System.out.println(s1.getAge());
65     }
66 }
67 */

 

posted @ 2021-02-17 16:29  奔啵儿灞  阅读(62)  评论(0)    收藏  举报