1. 程式人生 > >JAVA小白的入門日記—封裝

JAVA小白的入門日記—封裝

一.封裝的定義:

把物件的資訊和內部的邏輯結構基本隱藏起來

封裝的步驟

1.通過對屬性的可見性的修改限制對屬性的訪問。

2.為每個屬性建立一對賦值和取值方法

3.在賦值和取值方法中對屬性的存取進行限制。

二四種訪問控制符:

1、public:所修飾的類、變數、方法,在內外包均具有訪問許可權;

2、protected:這種許可權是為繼承而設計的,protected所修飾的成員,對所有子類是可訪問的,但只對同包的類是可訪問的,對外包的非子類是不可以訪問;

3、包訪問許可權(default):只對同包的類具有訪問的許可權,外包的所有類都不能訪問;

4、private:私有的許可權,只對本類的方法可以使用

*用一個表格來表示

這裡寫圖片描述

三.訪問控制符使用基本原則

1.類中的絕大部分成員都應該使用Private修飾,只有一些類似全域性變數的成員才考慮用public修飾。
2.如果一個類主要用做其他類的父類,該類中的方法希望被其子類重寫,而不是被其他類直接呼叫,則應該用Protected修飾這些方法。
3.希望暴露出來給其他類自由呼叫的方法應該使用public修飾。

this:this代表所在函式所屬物件的引用。

this的用法:當在方法內需要用到呼叫該方法的物件時,就用this。

下面還是附一段JAVA小白自己寫的入門程式碼

package com.lenovo.demo;

public
class Family { private String name; private String toothBrush; private String cardId; String telephone; public String cup; public String getName() { return name; } public void setName(String name) { if(name.length()>3) { this.name = name; } } static
String house; public String getToothBrush() { return toothBrush; } public void setToothBrush(String toothBrush) { this.toothBrush = toothBrush; } public String getCardId() { return cardId; } public void setCardId(String cardId) { this.cardId = cardId; } static String tv; public Family(String name,String toothBrush,String cardId,String telephone) { super(); this.name = name; this.toothBrush = toothBrush; this.cardId = cardId; this.telephone = telephone; } public void print() { System.out.println("我是 :"+this.name+",我用的牙刷是"+this.toothBrush+",我的身份證號是"+this.cardId+",我用的手機是"+this.telephone); } public static void main(String[] args) { Family child = new Family("巴巴","佳潔士","123456","vivo"); child.print(); child.setName("巴巴"); System.out.println(child.getName()); Family father = new Family("巴巴爸爸","雲南白藥","223456","oppo"); father.print(); Family mother = new Family("巴巴媽媽","高露潔","333456","小米"); mother.print(); }