2016-09-22

posted Sep 22, 2016, 7:10 AM by Samuel Konstantinovich   [ updated Sep 22, 2016, 1:11 PM ]
Goal Quiz + Mutator and Accessor methods.

This oracle page is a good read to help you understand how objects work:

I will go over a subset of this to explain what good Java style OOP looks like.



public class RunMe{
    public static void main(String[]args){
        Point p = new Point(5,3);
        //System.out.println(p.x);//no access to private
        System.out.println(p.getX());

        Rectangle s = new Rectangle();
        Rectangle r = new Rectangle(p);
        r.move(0,0);
        System.out.println(p.getX()+" "+p.getY());
    }
}



public class Point {
    private int x = 0;
    private int y = 0;
    // a constructor!
    public Point(int x, int y) {
        setX(x);
        setY(y);
    }

    // accessor methods
    public int getX(){
        return x;
    }
    public int getY(){
        return y;
    }

    //mutator methods
    public void setX(int x){
        this.x = x;
    }
    public void setY(int y){
        this.y = y;
    }

}


public class Rectangle {
    private int width = 0;
    private int height = 0;
    private Point origin;

    // four constructors
    public Rectangle() {
        origin = new Point(0, 0);
    }
    public Rectangle(Point p) {
        origin = p;
    }
    public Rectangle(int w, int h) {
        origin = new Point(0, 0);
        width = w;
        height = h;
    }
    public Rectangle(Point p, int w, int h) {
        origin = p;
        width = w;
        height = h;
    }
    // a method for moving the rectangle
    public void move(int x, int y) {
        origin.setX(x);
        origin.setY(y);
    }
    // a method for computing the area of the rectangle
    public int getArea() {
        return width * height;
    }
}
Comments