封装之详细详解
1.屬性私有,get/set
2.封裝:數據的隱藏
3.該漏漏,該藏藏:程序要求高內聚、低耦合,高內聚指類的內部數據操作細節自己完成,低耦合是提供少量方法供外部使用
package com.wuming.oop.demo04; //類 private:私有 public class Student {//屬性私有private String name;//名字private int id;//學號private char sex;//性別private int age;public int getAge() {return age;}public void setAge(int age) {if (age>120 || age<0){//不合法this.age=3;}else{this.age = age;}}//alt+insertpublic int getId() {return id;}public void setId(int id) {this.id = id;}//提供一些可以操作這個屬性的方法//提供一些public的get、set方法//get獲取這個數據public String getName(){return this.name;}//set給這個數據設置值public void setName(String name){this.name=name;} }同一個包下再創一個類
package com.wuming.oop.demo04;public class Application {public static void main(String[] args) {Student s1 = new Student();s1.setName("秦僵");System.out.println(s1.getName());s1.setAge(-1);//不合法的System.out.println(s1.getAge());} }秦僵
3
總結
- 上一篇: 多线程join,强制执行完
- 下一篇: Python abs函数 - Pytho