Accessor Methods

 

Since Java allows fields and methods to have the same name, some people prefer a class like this instead:

กก

class Point {

    private double x;
    private double y;
    
    public String toString() {
      return "(" + x + "," + y + ")";
    }
    
    void x(double value) {
      x = value;
    }
    
    void y(double value) {
      y = value;
    }
    
    int x() {
      return x;
    }
    
    int y() {
      return y;
    }
    
  }
  
}
Point origin = new Point();
origin.x(0.0);
origin.y(0.0);
System.out.println("The x coordinate is " + origin.x());


    

List | Previous | Next