HOWTO · Java
Java 中的私有方法
本教程演示了 Java 中私有方法的使用。
本頁內容
Java 中的私有方法有一個私有訪問修飾符,這意味著它們對定義類的訪問受到限制,並且在繼承的子類中不可訪問;這就是為什麼他們沒有資格覆蓋。
但是,可以在子類中建立一個方法,並且可以在父類中訪問該方法。本教程演示瞭如何在 Java 中建立和使用私有方法。
Java 中的私有方法
如上所述,私有方法只能在定義類中訪問;對於私有方法,我們考慮以下幾點。
- 私有方法是 Class X,只能在 Class X 中訪問。
- 包 X 的包私有成員或方法只能在 X 包的所有類中訪問。
讓我們嘗試在 Java 中建立和使用私有方法。參見示例:
package delftstack;
public class Private_Methods {
private void print() {
System.out.println("The Private Method can only be printed in the defining Class");
}
public static void main(String[] args) {
Private_Methods Demo = new Private_Methods();
Demo.print();
Private_Methods_Child Demo1 = new Private_Methods_Child();
Demo1.print();
}
}
class Private_Methods_Child extends Private_Methods {
public void print() {
System.out.println("The Public Method can be printed anywhere");
}
}
上面的程式碼建立了一個私有方法並在同一個類中呼叫它,同時也建立了一個公共方法在父類中呼叫它;輸出將是:
The Private Method can only be printed in the defining Class
The Public Method can be printed anywhere
如果我們在子類中將 public 方法改為 private,就會丟擲異常。參見示例:
package delftstack;
public class Private_Methods {
private void print() {
System.out.println("The Private Method can only be printed in the defining Class");
}
public static void main(String[] args) {
Private_Methods Demo = new Private_Methods();
Demo.print();
Private_Methods_Child Demo1 = new Private_Methods_Child();
Demo1.print();
}
}
class Private_Methods_Child extends Private_Methods {
private void print() {
System.out.println("The Public Method can be printed anywhere");
}
}
我們無法從子類訪問 print 方法。見輸出:
Exception in thread "main" java.lang.Error: Unresolved compilation problem:
The method print() from the type Private_Methods_Child is not visible
at delftstack.Private_Methods.main(Private_Methods.java:11)