Java基礎(八)Java封裝

封裝

封裝,是將類的某些信息隱藏在類內部,不允許外部程序直接訪問。

通過該類提供的方法來實現對隱藏信息的操作和訪問,作用:①隱藏對象的信息;②留出訪問的接口。

特點

1)只能通過規定的方法訪問數據;

2)隱藏類的實例細節,方便修改和實現。

實現步驟

修改屬性的可見性                                  ——    設爲private

創建getter/setter方法                             ——    設爲public 用於屬性的讀寫

在getter/setter方法中加入屬性控制語句 ——   對屬性值的合法性進行判斷

package com.pino.animal;

public class Cat {

    //成員屬性:暱稱、年齡、體重、品種

    //修改屬性的可見性——private 限定只能在當前類內訪問

    private String name;  //String類型默認值爲null

    private int month;    // int 類型默認值爲0

    private double weight;   //double 類型默認值爲0.0

    private String species;

    public Cat() {

        System.out.println("調用了無參構造方法");

    }

    public Cat(String name, int month, double weight, String species) {

        this.name = name;

        this.month = month;

        this.weight = weight;

        this.species = species;

    }

    //創建get/set方法,在get/set方法中添加對屬性的限定

    public String getName() {

        return name;

    }

    public void setName(String name) {

        this.name = name;

    }

    public int getMonth() {

        return month;

    }

    public void setMonth(int month) {

        if (month <= 0) {

            System.out.println("輸入信息錯誤");

        } else {

            this.month = month;

        }        

    }

    public double getWeight() {

        return weight;

    }

    public void setWeight(double weight) {

        this.weight = weight;

    }

    public String getSpecies() {

        return species;

    }

    public void setSpecies(String species) {

        this.species = species;

    }

}
package com.pino.animal;

public class CatTest {

    public static void main(String[] args) {

        //對象實例化

        Cat one = new Cat();

        one.setName("樂樂");

        one.setMonth(3);

        one.setWeight(11.0);

        one.setSpecies("短尾貓");

        //Cat one = new Cat("樂樂", 3, 11.0, "波斯貓");

        System.out.println("暱稱:"+one.getName());

        System.out.println("年齡:"+one.getMonth());

        System.out.println("體重"+one.getWeight());

        System.out.println("品種:"+one.getSpecies());

    }

}

 

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章