java other_在Java中,方法成为public / private / other是什么意思?
小編典典
當(dāng)一個(gè)方法 公開時(shí) ,意味著它可以被其他對(duì)象訪問(wèn)
例如:
class David {
// public method, can be use by anyone
public String getName() {
return "David";
}
}
該方法getName可以被其他類訪問(wèn),因?yàn)樗枪驳?#xff1a;
class Other {
David davidOne = new David();
String davidsName = davidOne.getName(); //
}
優(yōu)點(diǎn)..您可以從其他地方使用它。
如果方法是 私有的,*則意味著該方法只能由 同一類的 對(duì)象訪問(wèn)*
例如,在這個(gè)新定義中:
class David {
public String getName() {
return "David";
}
// private method... nobody but David's "instances" can use it..
private int getAge() {
return 19;
}
}
該方法getAge不能被其他類訪問(wèn),因?yàn)樗撬接械?#xff0c;如果嘗試這樣做,編譯器會(huì)給您一條錯(cuò)誤消息:
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();
}
}
優(yōu)勢(shì)?您可以創(chuàng)建一堆方法并將其保持私有狀態(tài),從而避免數(shù)據(jù)損壞或總體上保留封裝的對(duì)象
關(guān)于封裝
在OOP(面向?qū)ο蟪绦蛟O(shè)計(jì))中,其目的是根據(jù)現(xiàn)實(shí)生活中的對(duì)象對(duì)軟件進(jìn)行建模。
現(xiàn)實(shí)生活中的對(duì)象具有(除其他外)屬性和訪問(wèn)這些屬性的方法。
您想公開其中一些方法,而另一些保持私有。
例如, 人類 有一顆心。但是它并沒(méi)有暴露給所有人,這很危險(xiǎn)。它被 包裹 在我們體內(nèi)。
如果我們要以真實(shí)的 人類 為模型來(lái)建模,我們可以將方法聲明為:heartBeat 私有的(因此,沒(méi)有人可以訪問(wèn)它)
另一方面,采用 公共 方法getGender來(lái)查找您的 Human 實(shí)例是男性還是女性,這將是有用的。
還有其他訪問(wèn)修飾符,例如:“ protected”和受保護(hù)的軟件包(其沒(méi)有關(guān)鍵字)
class David {
// protected method
protected int getBalance() {
return 1000000;
}
// package protected or "default" method
boolean knowsOop(){
return true;
}
}
在那里,該方法getBalance只能由David實(shí)例和David子類訪問(wèn)(為子類創(chuàng)建另一個(gè)線程)
knowsOop 定義David時(shí),包內(nèi)的任何人都可以訪問(wèn)該方法。
不用擔(dān)心這兩個(gè)訪問(wèn)修飾符,當(dāng)您了解有關(guān)OOP和Java的更多信息時(shí),它們將很有意義。
最后,您應(yīng)該花時(shí)間閱讀以下內(nèi)容:
我希望這有幫助
2020-10-09
總結(jié)
以上是生活随笔為你收集整理的java other_在Java中,方法成为public / private / other是什么意思?的全部?jī)?nèi)容,希望文章能夠幫你解決所遇到的問(wèn)題。
- 上一篇: 【嵌入式开发教程6】手把手教你做平板电脑
- 下一篇: 一键创建多个文件夹?快速批量建立文件夹并