Java 中 protected 和 default 訪問修飾符有什麼區別?
**Protected** 訪問修飾符在**同一包內可見**,並且在**子類中也可見**,而**Default** 是一個**包級訪問修飾符**,它可以在**同一包內可見**。
Protected 訪問修飾符
- **Protected** 在同一包內起作用類似於 public,而在包外起作用類似於 private。
- **Protected** 僅對子類物件在包外也起作用類似於 public。
- **Protected** 欄位或方法不能用於類和介面。
- 在超類中宣告為 **protected** 的欄位、方法和建構函式只能被其他包中的子類訪問。
- 同一包中的類也可以訪問 **protected** 欄位、方法和建構函式,即使它們不是 **protected** 成員所屬類的子類。
示例
public class ProtectedTest {
// variables that are protected
protected int age = 30;
protected String name = "Adithya";
/**
* This method is declared as protected.
*/
protected String getInfo() {
return name +" is "+ age +" years old.";
}
public static void main(String[] args) {
System.out.println(new ProtectedTest().getInfo());
}
}輸出
Adithya is 30 years old.
Default 訪問修飾符
- 如果類成員**沒有任何訪問修飾符**,則認為它是 **Default**。
- **Default** 在同一包內起作用類似於 public,而在包外起作用類似於 private。
- 任何類的 **Default** 成員都可以被同一包內的任何內容訪問,但在任何情況下都不能在包外訪問。
- **Default** 將訪問許可權限制在**包級別**,即使擴充套件了具有預設資料成員的類,我們也無法訪問。
示例
public class DefaultTest {
// variables that have no access modifier
int age = 25;
String name = "Jai";
/**
* This method is declared with default aacees specifier
*/
String getInfo() {
return name +" is "+ age +" years old.";
}
public static void main(String[] args) {
System.out.println(new DefaultTest().getInfo());
}
}輸出
Jai is 25 years old.
廣告
資料結構
網路
關係資料庫管理系統
作業系統
Java
iOS
HTML
CSS
Android
Python
C 程式設計
C++
C#
MongoDB
MySQL
Javascript
PHP