android - 公共(public)或私有(private),Android变量真的很重要吗

标签 android memory private public

在单个 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/

相关文章:

api - Apple 应用指南——私有(private) API?

java - 字段没有私有(private) setter - 单元测试遗留代码

android - 从不起作用的位图中创建或剪切 6 个相等的部分

android - 如何在多个 Activity 中显示相同的对话框?

python - 标准差的 NumPy 函数的内存消耗

java - 使用进程 ID 获取进程的实际内存使用情况

c - 错误 : "pointer being freed was not allocated" in c

android - 使用 MVVM 改造

android - 在 Google Play 服务排行榜上隐藏虚假分数

javascript - 设置与函数参数同名的 Javascript 私有(private)变量?