在单个 Activity 中,当定义仅在该 Activity 中使用的组件时,以下定义之间的真正区别是什么:
Button btnPower = null;
//or
private Button btnPower = null;
//or
public Button btnPower = null;
public void somethingUsingTheButton(){
btnPower = (Button)findViewById(R.id.btnpower_id);
}
是否应该考虑一些“幕后”约定(垃圾清理、内存等),如果实体本身只在类内部使用,则建议始终使用私有(private)而不是公共(public)写的?
最佳答案
私有(private)领域推广 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 );
}
}
}
关于android - 公共(public)或私有(private),Android变量真的很重要吗,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12500913/