私有字段促进封装
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 );
}
}
}