封装

介绍

概述:Encapsulation根据不同的功能,进行不同的(功能类似)封装 需要时调用,无需编写。

属性私有,隐藏对象属性和内部实现细节,对外提供访问方式。

函数就是最小的封装。

开发原则:高内聚,低耦合。

好处:提高代码安全性与复用性。

权限控制符

在一个项目下

修饰符

本类

本包

本包/其它包子类

所有包

private

default

protected

public

注意:类只能使用public与default,内部类(后面会讲)4个修饰符随便用。

封装使用细节

示例

package com.itcode.demo;  


/**      
 * @author: 成都码到功成学员  
 * @Description:  
 * overwrite方法重写 
 */  


class TestEnc {  

    // 私有化属性  
    private int age;  
    private String name;  
    private boolean human;  

    // 对外提供访问方式。  
    /** 
     * @return the age 
     */  
    public int getAge() {  
        return age;  
    }  
    /** 
     * @param age the age to set 
     */  
    public void setAge(int age) {  
        // 在里面做一些逻辑,外界无法查看  
        if( age>18) {  
            System.out.println("成年了");  
            this.age = age;  
        }else {  
            System.out.println("还小");  
        }  
    }  
    /** 
     * @return the name 
     */  
    public String getName() {  
        return name;  
    }  
    /** 
     * @param name the name to set 
     */  
    public void setName(String name) {  
        this.name = name;  
    }  
    /** 
     * @return the human 
     * 记住 布尔类型的get方法是这样的。isXXX(); 
     */  
    public boolean isHuman() {  
        return human;  
    }  
    /** 
     * @param human the human to set 
     */  
    public void setHuman(boolean human) {  
        this.human = human;  
    }  


}  

public class TestEncapsulation {  

    public static void main(String[] args) {  
        TestEnc enc = new TestEnc();  
        enc.setAge(23);  
    }   
}

Last updated

Was this helpful?