java other_在Java中,方法成为public / private / other是什么意思?
小編典典
當一個方法 公開時 ,意味著它可以被其他對象訪問
例如:
class David {
// public method, can be use by anyone
public String getName() {
return "David";
}
}
該方法getName可以被其他類訪問,因為它是公共的:
class Other {
David davidOne = new David();
String davidsName = davidOne.getName(); //
}
優點..您可以從其他地方使用它。
如果方法是 私有的,*則意味著該方法只能由 同一類的 對象訪問*
例如,在這個新定義中:
class David {
public String getName() {
return "David";
}
// private method... nobody but David's "instances" can use it..
private int getAge() {
return 19;
}
}
該方法getAge不能被其他類訪問,因為它是私有的,如果嘗試這樣做,編譯器會給您一條錯誤消息:
class Other {
David davidOne = new David();
String davidsName = davidOne.getName();
int davidsAge = davidOne.getAge(); //
}
但是,如果可以 在 David類中使用它:
class David {
public String getName() {
return "David";
}
// private method... nobody but David's "instance" can use it..
private int getAge() {
return 19;
}
// Here the call to "getAge()" will succeed, because it is visible
// inside the class
public boolean hasSameAgeAs( David otherDavid ) {
return this.getAge() == otherDavid.getAge();
}
}
優勢?您可以創建一堆方法并將其保持私有狀態,從而避免數據損壞或總體上保留封裝的對象
關于封裝
在OOP(面向對象程序設計)中,其目的是根據現實生活中的對象對軟件進行建模。
現實生活中的對象具有(除其他外)屬性和訪問這些屬性的方法。
您想公開其中一些方法,而另一些保持私有。
例如, 人類 有一顆心。但是它并沒有暴露給所有人,這很危險。它被 包裹 在我們體內。
如果我們要以真實的 人類 為模型來建模,我們可以將方法聲明為:heartBeat 私有的(因此,沒有人可以訪問它)
另一方面,采用 公共 方法getGender來查找您的 Human 實例是男性還是女性,這將是有用的。
還有其他訪問修飾符,例如:“ protected”和受保護的軟件包(其沒有關鍵字)
class David {
// protected method
protected int getBalance() {
return 1000000;
}
// package protected or "default" method
boolean knowsOop(){
return true;
}
}
在那里,該方法getBalance只能由David實例和David子類訪問(為子類創建另一個線程)
knowsOop 定義David時,包內的任何人都可以訪問該方法。
不用擔心這兩個訪問修飾符,當您了解有關OOP和Java的更多信息時,它們將很有意義。
最后,您應該花時間閱讀以下內容:
我希望這有幫助
2020-10-09
總結
以上是生活随笔為你收集整理的java other_在Java中,方法成为public / private / other是什么意思?的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 【嵌入式开发教程6】手把手教你做平板电脑
- 下一篇: java美元兑换,(Java实现) 美元