如何在Java中完全封裝一個物件?
將資料和作用於資料的程式碼封裝在一起的過程稱為封裝。這是一種保護機制,我們透過它隱藏一個類的資料,使其無法被另一個類(的物件)訪問。
由於變數儲存類的變數,因此要封裝一個類,您需要將所需的變數(您想要隱藏的變數)宣告為私有,並提供公共方法來訪問(讀取/寫入)它們。
透過這樣做,您只能在當前類中訪問變數,它們將對其他類隱藏,並且只能透過提供的方法訪問。因此,它也被稱為資料隱藏。
完全封裝類/物件
要完全封裝一個類/物件,您需要
- 將類中所有變數宣告為私有。
- 提供公共的setter和getter方法來修改和檢視它們的值。
示例
在下面的 Java 程式中,**Student** 類有兩個變數 name 和 age。我們透過將它們設為私有並提供 setter 和 getter 方法來封裝此類。
如果您想訪問這些變數,則不能直接訪問它們,您只能使用提供的 setter 和 getter 方法來讀取和寫入它們的值。您沒有為其提供這些方法的變數將完全對外部類隱藏。
import java.util.Scanner; class Student { private String name; private int age; public int getAge() { return age; } public void setAge(int age) { this.age = age; } public String getName() { return name; } public void setName(String name) { this.name = name; } public void display() { System.out.println("name: "+getName()); System.out.println("age: "+getAge()); } } public class AccessData{ public static void main(String args[]) { //Reading values from user Scanner sc = new Scanner(System.in); System.out.println("Enter the name of the student: "); String name = sc.nextLine(); System.out.println("Enter the age of the student: "); int age = sc.nextInt(); //Calling the setter and getter methods Student obj = new Student(); obj.setName(name); obj.setAge(age); obj.display(); } }
輸出
Enter the name of the student: Krishna Enter the age of the student: 20 name: Krishna age: 20
廣告