面向对象之封装

75 阅读2分钟

封装

理念:高内聚,低耦合。 高内聚:类的内部数据操作细节自己完成,不允许外部干涉;低耦合:仅暴露少量的方法给外部使用,尽量方便外部调用。

优点

  1. 提高代码的安全性
  2. 提高代码的复用性
  3. “高内聚”封装细节,便于修改内部代码,提高可维护性
  4. “低耦合”简化外部调用,便于调用者使用,便于扩展和协作

Java通过使用“访问控制符”来控制细节需要封装

四种访问修饰符

  1. private 同一个类
  2. defult 同一个类、同一个包
  3. protected 同一个类、同一个包、子类
  4. public 同一个类、同一个包、子类、所有类

注意: 若父类和子类在同一个包中,子类可访问父类的protected成员,也访问父类对象的protected成员

若子类和父类不在同一个包中,子类可访问父类的protected成员,不能访问父类对象的protected成员

测试:


package com.itbaizhan.tast.encapsulation.a;

public class Person {
    private  int testPrivate;
             int testDefault;
    protected int testProtected;
    public   int testPublic;

    public void test(){
        System.out.println(this.testPrivate);
    }

}





ackage com.itbaizhan.tast.encapsulation.a;

public class Student extends Person {


    public void study(){
        System.out.println(super.testProtected);
        Person p = new Person();
        //System.out.println(p.testPrivate);私有的。不能访问
        System.out.println(p.testDefault);
        System.out.println(p.testProtected);
        System.out.println(p.testPublic);
    }
}


package com.itbaizhan.tast.encapsulation.b;

import com.itbaizhan.tast.encapsulation.a.Person;

public class Boy  extends Person {

    public void play(){
        System.out.println(super.testProtected);
        System.out.println(super.testPublic);//defult不在同一个包中,不能访问

        Person p = new Person();
        //System.out.println(p.testProtected);不在同一个包中,不能访问父类对象protected成员
    }
}

#Javaben概念#

开发中封装的简单规则

  1. 属性一般使用privte访问权限。 属性私有后,提供相应的get/set方法来访问香相关属性,这些方法通常是public修饰的,以提供对属性的赋值与读取操作(注意:boolean的变量的get/方法是is开头!)
  2. 方法:一些值用于本类的辅助性方法可以用private修饰,希望其他类调用的方法用public修饰

测试:

package com.itbaizhan.tast.encapsulation.b;

public class User {
    private int id;
    private String name;
    private boolean man;

    public User(int id, String name, boolean man) {
        this.id = id;
        this.name = name;
        this.man = man;
    }

    public void printUserInfo(){//public私有的,方便外部外部调用

    }

    public int getId() {//获得值
        return id;
    }

    public void setId(int id) {//如果要设置,直接赋值
        this.id = id;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public boolean isMan() {
        return man;
    }

    public void setMan(boolean man) {
        this.man = man;
    }
}

package com.itbaizhan.tast.encapsulation.b;

public class Test {

    public static void main(String[] args){
        User u = new User(99,"王誉", true);
        u.setId(100);
        u.setName("王誉");
        u.setMan(true);


        System.out.println(u.getName());
        System.out.println(u.isMan());
    }
}