java中set和get方法

import java.awt.Color;
public class Point{
private int x;
private int y;
private Color mycolor;
public Point(){
}
public Point(int x,int y){
this.x=x;
this.y=y;
}
public Point(int x,int y,Color mycolor){
this.x=x;
this.y=y;
this.mycolor=mycolor;
}
//从这里开始
public int getX() {
return x;
}
public void setX(int x) {
this.x = x;
}
public int getY() {
return y;
}
public void setY(int y) {
this.y = y;
}
public Color getColor() {
return color;
}
public void setColor(Color color) {
this.color = color;//到这里结束一定要有么,是在定义set和get方法么?

public int distance (Point another){
return (int)Math.sqrt((this.x-another.x)*(this.x-another.x)+(this.y-another.y)*(this.y-another.y));

}
public boolean equals(Point another){
return (this.x==another.x&&this.y==another.y)?true:false;
}
public String toString(){
return "("+x+","+y+")color:"+mycolor;
}
public static void main(String[] args){
Point A=new Point();
Point B=new Point(50,60);
Point C=new Point(100,200,Color.yellow);

System.out.println("B: "+B);
A.setX(100);
A.setY(200);
A.setColor(Color.yellow);
System.out.println("A :"+A);
System.out.println("A==B? "+A.equals(B));
System.out.println("A->B "+A.distance(B));
}

}

第1个回答  2012-04-20
从本质上说,不一定要写get和set方法。
写get和set方法只是为了更好的对Point这个类的属性方便的处理。
只是大家默认的写法。
set方法顾名思义:对new的来的对象进行属性设定。
get方法:通过return 返回(或者说是拿到)类的属性值。
只是为了方便。
第2个回答  2012-04-20
一般来说是要有set()和get()方法的.因为JAVA有三要素,第一就是封装,把类里面的属性全部写成私有的以后就可以保持类的安全性,但是在其他类中又需要使用到这些私有的属性,所有JAVA就会给每个私有的属性定义两个公有的方法,方便赋值和取值!
第3个回答  2012-04-20
get和set方法可以在编辑框按快捷键 alt+shift+s 选择get和set方法生成;这2个方法主要是用来赋值和获取值的,根据需要进行选择。
第4个回答  2012-04-20
如果需要设定color的值就需要set方法
第5个回答  2012-04-20
当然得有,不然在mian()方法里面,实例化的对象A,怎么访问自己私有的成员属性和方法?本回答被提问者采纳