Final classes in Java

Bertil Muth - Jul 1 '18 - - Dev Community

There have been some discussions about the final keyword applied to classes in Java. To put it simple: when a class is declared final, you can't create a sub class of it.

An example would be helpful now.
Say this is your class:

public final class PopBand {
    public void hereIAm() {
        System.out.println("Here I am");
    }
    public void willYouSendMeAnAngel() {
        System.out.println("Will you send me an angel?");
    }
}
Enter fullscreen mode Exit fullscreen mode

If you try to create a sub class, the compiler will give you an error:

// This will cause a compile error
public class RockBand extends PopBand {
}
Enter fullscreen mode Exit fullscreen mode

What you can do, though, is extend the class by using composition.
That is: you create another class that contains an object of the original class. And then you delegate to the original (for the original's methods). And you add new methods. Like this:

public class PopRockBand {
    /**
     * Create an object of the class PopBand and assign it to containedBand
     */
    PopBand containedBand = new PopBand();

    /**
     * Delegate to methods of PopBand 
     */

    public void hereIAm() {
        containedBand.hereIAm();
    }

    public void willYouSendMeAnAngel() {
        containedBand.willYouSendMeAnAngel();
    }

    /**
     * This method is specific to PopRockBand class
     */
    public void rockYouLikeAHurricane() {
        System.out.println("Rock you like a hurricane");
    }
}
Enter fullscreen mode Exit fullscreen mode

And here's the Main class that proves composition works:

public class Gig {
    public static void main(String[] args) {
        PopRockBand scorpions = new PopRockBand();

        // Play "Send me an angel"
        scorpions.hereIAm();
        scorpions.willYouSendMeAnAngel();

        // Play "Rock you like a hurricane"
        scorpions.hereIAm();
        scorpions.rockYouLikeAHurricane();
    }
}
Enter fullscreen mode Exit fullscreen mode
. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .