set和get方法与public变量的优点

zzz*_*zzz 49 java methods private class public

可能重复:
为什么要使用getter和setter?

制作方法来访问类中的私有变量而不是将变量公开是否有任何优势?

例如,第二种情况比第一种情况好吗?

//Case 1
public class Shoe{
    public int size;
}

//Case 2
public class Shoe{
    private int size;
    public int getSize(){
        return size;
    }

    public void setSize(int sz){
        size = sz;
    }

}
Run Code Online (Sandbox Code Playgroud)

dan*_*uch 82

我有一天在SO上看到的,作为答案(由@ ChssPly76编写)为什么要使用getter和setter

因为从现在起2周(几个月,几年),当你意识到你的setter需要做的不仅仅是设置值时,你也会意识到该属性已被直接用于其他238个类:-)

还有更多优点:

  1. getter和setter 可以在其中进行验证,字段不能
  2. 使用getter,您可以获得所需类的子类.
  3. getter和setter 是多态的,字段不是
  4. 调试可以简单得多,因为断点可以放在一个方法内,而不是靠近给定字段的许多引用.
  5. 他们可以隐藏实施变化:

之前:

private boolean alive = true;

public boolean isAlive() { return alive; }
public void setAlive(boolean alive) { this.alive = alive; }
Run Code Online (Sandbox Code Playgroud)

后:

private int hp; // change!

public boolean isAlive() { return hp > 0; } // old signature 
 //method looks the same, no change in client code
public void setAlive(boolean alive) { this.hp = alive ? 100 : 0; }
Run Code Online (Sandbox Code Playgroud)

编辑:当你使用Eclipse时另外一个新的优势 - 你可以在字段上创建观察点,但是如果你有setter你只需要一个断点,并且...... 断点(例如在setter方法中)可以是有条件的,观察点(在字段上)不能.因此,如果您只想x=10在setter中使用断点来执行此操作,则只需要停止调试器.


Kum*_*tra 8

使用公共变量可能会导致为变量设置错误的值,因为无法检查输入值.

例如:

 public class A{

    public int x;   // Value can be directly assigned to x without checking.

   }
Run Code Online (Sandbox Code Playgroud)

使用setter可以通过检查输入来设置变量.保持实例varibale私有,getter和setter public是Encapsulation getter的一种形式,setter也兼容Java Beans标准,

getter和setter也有助于实现多态性概念

例如:

public class A{

     private int x;      //


      public void setX(int x){

       if (x>0){                     // Checking of Value
        this.x = x;
       }

       else{

           System.out.println("Input invalid");

         }
     }

      public int getX(){

          return this.x;
       }
Run Code Online (Sandbox Code Playgroud)

多态示例:我们可以将Sub类型的Object Refernce变量作为Argument从Calling方法分配给被调用方法的Super Class Parameter的Object Refernce变量.

public class Animal{

       public void setSound(Animal a) {

          if (a instanceof Dog) {         // Checking animal type

                System.out.println("Bark");

             }

         else if (a instanceof Cat) {     // Checking animal type

                 System.out.println("Meowww");

             }
         }
      }
Run Code Online (Sandbox Code Playgroud)


yan*_*kee 5

  1. 一些库要求使用它来满足“ Java Bean标准”。
  2. 设置器/获取器可以位于接口中,属性不能位于接口中
  3. 设置器/获取器可以很容易地在降级类中被覆盖。
  4. 设置者/获取者将信息抽象出来,无论是按需计算值还是仅仅是属性的访问者