【问题标题】:Difference ways to assign variable in java? [closed]在java中分配变量的不同方法? [关闭]
【发布时间】:2012-08-12 12:38:17
【问题描述】:

分配java变量的最佳方式是什么?有什么区别?看到这个;

   public class Test {
       private String testString;

       //getter & setter here.

       public void testMethodOne() {
            this.testString = "Hello World!";
       }

        public void testMethodTwo() {
            testString = "Hello World!";
       }

        public void testMethodThree() {
            setTestString("Hello World!");
       }
   }

哪个最好,this.testString = "xxx"testString = "xxx"setTestString("xxx")

【问题讨论】:

  • 请阅读 Joshua Bloch 的 Effective Java 中的第 13-14 条。
  • 我发现不必要地使用this. 会给眼睛带来负担,但这是一个品味问题。在类内部调用 setTestString 是不必要的,除非您知道它除了修改值之外还有有用的副作用。
  • @AmitDeshpande 第 13 项或第 14 项与此处无关。
  • 顺便说一句,这会产生编译错误,严重的是在运行时它会生成相同的字节码

标签: java variable-assignment


【解决方案1】:

正如@dadu 提到的,您应该使用this,就像我们在帮助类(setter/getter)方法中使用的那样。

如果您使用任何其他类而不是辅助类(没有任何 setter/getter),则始终建议使用 constructor 。使用 constructor 并分配变量值。基本上构造函数的目的是初始化成员变量。构造函数示例如下:-

private int intUerId,intUserType,intBranchId;
private String vchUserName,vchFullName,vchPrivilege;

public LoginBean(int intUerId, String vchUserName, String vchFullName,
            String vchPrivilege,int intUserType,int intBranchId) {
        super();
        this.intUerId = intUerId;
        this.vchUserName = vchUserName;
        this.vchFullName = vchFullName;
        this.vchPrivilege = vchPrivilege;
        this.intUserType=intUserType;
        this.intBranchId=intBranchId;
    }

【讨论】:

    【解决方案2】:

    我建议您在类属性前加上“this”。这样您就可以更好地了解成员变量与局部变量。
    当您无法直接访问类属性(从另一个类访问它们)时,请使用 getter/setter。

    【讨论】:

      猜你喜欢
      • 2016-06-07
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-02-23
      • 1970-01-01
      • 1970-01-01
      • 2011-09-25
      • 1970-01-01
      相关资源
      最近更新 更多