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个类:-)
还有更多优点:
之前:
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中使用断点来执行此操作,则只需要停止调试器.
使用公共变量可能会导致为变量设置错误的值,因为无法检查输入值.
例如:
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)
归档时间: |
|
查看次数: |
51197 次 |
最近记录: |