Skip to content

Instantly share code, notes, and snippets.

@njlr
Last active November 7, 2018 16:11
Show Gist options
  • Save njlr/c6d17cce1c69c441bdb4ed445cec54ee to your computer and use it in GitHub Desktop.
Save njlr/c6d17cce1c69c441bdb4ed445cec54ee to your computer and use it in GitHub Desktop.

Encapsulation in Java ☕

Today we are going to learn about encapsulation using Java!

OK! Let's write a vector class...

public class Vector2 {
    public float x;
    public float y;
}

Hang on... public fields are Bad Practice... what if they were to change in the future? We should be designing to an interface.

public interface Vector2 {
    float getX();
    float getY();
}

Better make those fields private!

public final class BasicVector2 implements Vector2 {
    private float x;
    private float y;
    
    public float getX() {
        return x;
    }
    
    public float getY() {
        return y;
    }
    
    public BasicVector2(float x, float y) {
        this.x = x;
        this.y = y;
    }
}

Hmmm... but we still need to be able to modify the vector!

Let's extend the interface...

public interface Vector2 {
    float getX();
    float getY();
    
    Vector2 setX(float x);
    Vector2 setY(float y);
}

... and the implementation.

public final class BasicVector2 implements Vector2 {
    private float x;
    private float y;
    
    public float getX() {
        return x;
    }
    
    public float getY() {
        return y;
    }
    
    public Vector2 setX(float x) {
        this.x = x;
        return this;
    }
    
    public Vector2 setY(float y) {
        this.y = y;
        return this;
    }
    
    public BasicVector2(float x, float y) {
        this.x = x;
        this.y = y;
    }
}

Isn't that so much better?

Now our data is encapsulated behind getters and setters!

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment