Home

Awesome

Object-Oriented Programming concepts recap with Java examples

Concept

Classes vs objects

Visibility and inheritance

public, protected, and private visibility keywords

        "Child#privateMethod Child#protectedMethod Child#publicMethod" // a
        "Parent#privateMethod Child#protectedMethod Child#publicMethod" // b
        "Parent#privateMethod Parent#protectedMethod Child#publicMethod" // c
        "Parent#privateMethod Child#protectedMethod Parent#publicMethod" // d
        "Parent#privateMethod Parent#protectedMethod Parent#publicMethod" // e
        // It doesn't compile // f

static keyword

Counter counterA = new Counter();
Counter counterB = new Counter();
Counter counterC = new Counter();

counterA.increaseTotal();
counterA.increaseTotal();
counterA.increaseTotal();

counterB.increaseTotal();
counterB.increaseTotal();

counterC.increaseTotal();

// a:
counterA.getTotal(); // 0
counterB.getTotal(); // 0
counterC.getTotal(): // 0

// b:
counterA.getTotal(); // 6
counterB.getTotal(); // 6
counterC.getTotal(): // 6

// c:
counterA.getTotal(); // 3
counterB.getTotal(); // 5
counterC.getTotal(): // 6

// c:
counterA.getTotal(); // 6
counterB.getTotal(); // 3
counterC.getTotal(): // 1

final keyword

abstract classes vs interfaces


interface ProductRecommender
{
    Recommendations findFor(ProductId productId);
}

final class BlueknowProductRecommender implements ProductRecommender
{
    @Override
    public Recommendations findFor(ProductId productId) {
        // Call to the Blueknow service API
        // Parse the JSON response into a `Recommendations` class instance
        return recommendations;
    }
}

Example: