Basic Java Class Structure

Basic knowledge for IB Computer Science is the structure of a Java class. You should be able to create the class, its instance variables, constructor, get and set methods, and a toString() method, without even need to stop and think.

Question:

Create a Point class that has two instance variables x and y, corresponding to its coordinates on the Cartesian plane. Include an appropriate constructor that initialises these variables. Encapsulate the variables and provide a toString() method.

Answer:

public class Point {
   private int x;
   private int y;

   public Point(int x, int y) {
       setX(x);
       setY(y);
   }

   public int getX() {
      return x;
   }

   public int getY() {
      return y;
   }

   public void setX(int x) {
      this.x = x;
   }

   public void setY(int y) {
      this.y = y;
   }

   public String toString() {
      return "(" + x + "," + y +")";
   }
}

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s