Oct*_*rpe 26 memory android private public
在单个活动内部,当定义仅在该活动中使用的组件时,以下定义之间的真正区别是什么:
Button btnPower = null;
//or
private Button btnPower = null;
//or
public Button btnPower = null;
public void somethingUsingTheButton(){
btnPower = (Button)findViewById(R.id.btnpower_id);
}
Run Code Online (Sandbox Code Playgroud)
是否有一些"引擎盖下"的约定应该被考虑(垃圾清理,内存等),这些约定会建议总是使用私有公共,如果实体本身只会在它所写的类中使用?
pjc*_*jco 28
私有领域促进封装
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 );
}
}
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
11893 次 |
| 最近记录: |