私人領域推廣encapsulation
這是普遍接受的慣例,除非你需要的字段或方法暴露給其他類使用private
。作爲一種習慣進入這將會爲你節省很多痛苦,從長遠來看。
然而,public
字段或方法沒有任何內在錯誤。它對垃圾收集沒有影響。
在某些情況下,某些類型的訪問會影響性能,但它們可能比此問題的主題稍高一些。
一個這樣的情況與內部類訪問外部類字段有關。
class MyOuterClass
{
private String h = "hello";
// because no access modifier is specified here
// the default level of "package" is used
String w = "world";
class MyInnerClass
{
MyInnerClass()
{
// this works and is legal but the compiler creates a hidden method,
// those $access200() methods you sometimes see in a stack trace
System.out.println(h);
// this needs no extra method to access the parent class "w" field
// because "w" is accessible from any class in the package
// this results in cleaner code and improved performance
// but opens the "w" field up to accidental modification
System.out.println(w);
}
}
}
大多數情況下,尤其是在您描述一切僅在一個類/活動中的場景中,它只是一種很好的形式,可以將範圍限制爲您使用的任何變量。 –