JAVA编程创建一个Point类

来源:百度知道 编辑:UC知道 时间:2024/05/09 05:46:26
编程创建一个Point类,在其中定义两个变量表示一个点的坐标值,再定义构造函数初始化为坐标原点,然后定义一个方法实现点的移动,再定义一个方法打印当前点的坐标。并创建一个对象验证。
提示:关键代码如下:
void move(int newX,int newY){
x=newX;
y=newY;
}
void print(){
System.out.println(name+":x="+x+" y="+y);
}

p.print();
p.move(50,50);
System.out.println("**after moving**");
p.print(); //call method of an object

public class Point
{
private int x;
private int y;
private String name;
public Point()
{
this.x = 0;
this.y = 0;
this.name = "default";
}

public Point(int x,int y,String name)
{
this.x = x;
this.y = y;
this.name = name;
}

public void move(int newX,int newY)
{
x = newX;
y = newY;
}

public void print()
{
System.out.println(name+":x="+x+" y="+y);
}

public static void main (String[] args)
{
Point p1 = new Point();
p1.print();
p1.move(50,50);
System.out.println("**after moving**");
p1.print();

Point p2 = new Point(10,10,"Point2");
p2.print();
p2.move(150,150);
System.out.println("**after moving**");
p2.print();
}
}