class Point{
private int x;
private int y;
public Point(int x,int y){
this.x=x;
this.y=y;
}
public void move(int xSet,int ySet){
this.x+=xSet;
this.y+=ySet;
}
}
public class Test1{
public static void main(String[]args){
Point myP=new Point(10,10);
System.out.println("Point:x="+myP.x+"y="+myP.y+"\n");
myP.move(10,10);
System.out.println("Point:x="+myP.x+"y="+myP.y+"\n");
}
}
错误指令:
x ,y可以在point中访问private该怎么解决 收起
private int x;
private int y;
public Point(int x,int y){
this.x=x;
this.y=y;
}
public void move(int xSet,int ySet){
this.x+=xSet;
this.y+=ySet;
}
}
public class Test1{
public static void main(String[]args){
Point myP=new Point(10,10);
System.out.println("Point:x="+myP.x+"y="+myP.y+"\n");
myP.move(10,10);
System.out.println("Point:x="+myP.x+"y="+myP.y+"\n");
}
}
错误指令:
x ,y可以在point中访问private该怎么解决 收起
2010-07-24 13:02
最佳答案
因为xy是private变量,你需要加上设置和读取的方法: public int getX(){ return this.x; } public void setX(int s){ this.x = x; } 然后从外部访问的时候只能通过调用getX()和setX来读取和写入。y的你自己写一下,当作作业。 System.out.println("Point:x=" + myP.getX() + "y=" + myP.getY() + "\n");

为啥我加了setter也不好使?...不是可以通过构造方法初始化的嘛?