简体   繁体   English

其他方法中的eclipse自动getter和setter方法

[英]eclipse auto getter and setter method in other method

This is simple class implementation 这是简单的类实现

class A{
private int a;
public void doSomething() {
    a = 5;
    int b = a;
    /*.
      .
      . */
}
/*
.
.
. */
}

now i'm using eclipse CTRL + 1 quick fix keybind and insert get and set mothod and codes will be this and this is option 1 现在我正在使用eclipse CTRL + 1快速修复keybind并插入get和set mothod和代码将是这个,这是选项1

class A{
private int a;
public void doSomething() {
    setA(5);
    int b = getA();
    /*.
      .
      . */
}
/*
.
.
. */
public int getA() {
    return a;
}
public void setA(int a) {
    this.a = a;
}
}

but if i want keep field codes will be this.(option 2) 但如果我想保持字段代码将是这个。(选项2)

class A{
private int a;
public void doSomething() {
    a = 5;
    int b = a;;
    /*.
      .
      . */
}
/*
.
.
. */
public int getA() {
    return a;
}
public void setA(int a) {
    this.a = a;
}
}

so which option is better for oop or code organization. 那么哪个选项更适合oop或代码组织。

If you want to keep the normal assignment of a (ie a = 5; ) inside doSomething instead of using the setter ( setA(5) ), try creating the getters and setters using the refactoring key binding Alt + Shift + s and then select "Generate Getters and Setters". 如果你想在doSomething保持a (即a = 5; )的正常分配而不是使用setter( setA(5) ),尝试使用重构键绑定Alt + Shift + s创建getter和setter,然后选择“生成吸气剂和二传手”。

If the only thing the setter does is assign the value to the field, there should be no difference between the two options. 如果setter做的唯一事情是将值赋给字段,那么两个选项之间应该没有区别。

If I understand you, then you could make int setA(int) also return a; 如果我理解你,那么你可以使int setA(int)return a; , and then you can "chain" the method calls ,然后你可以“链接”方法调用

public int setA(int a) {
  this.a = a;
  return a;
}

public void doSomething() {
  int b = setA(5);
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM