Wednesday 7 April 2010

JAVA "toString" Method

Class

public class Vehicle {
private int x = 0;
private int y = 0;
void moveUp() {
this.y = y + 1;
}
void moveDown() {
this.y = y - 1;
}
void moveLeft() {
this.x = x - 1;
}
void moveRight() {
this.x = x + 1;
}
public String toString() {
return "(" + this.x +","+ this.y + ")";
}

}

Driver
public class VehicleUser{
public static void main(String[] args){
Vehicle car1 = new Vehicle();
System.out.println("The co-ordinate is:" + car1);
car1.moveUp();
System.out.println("For moveUp" + car1);
Vehicle car2 = new Vehicle();
System.out.println("The co-ordinate is:" + car2);
car2.moveDown();
System.out.println("For moveDown" + car2);
Vehicle car3 = new Vehicle();
System.out.println("The co-ordinate is:" + car3);
car3.moveRight();
System.out.println("For moveRight" + car3);
Vehicle car4 = new Vehicle();
System.out.println("The co-ordinate is:" + car4);
car4.moveLeft();
System.out.println("For moveLeft" + car4);
}
}

No comments:

Post a Comment