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?");
}
}
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 {
}
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");
}
}
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();
}
}
Top comments (8)
@bertilmuth Thanks for explaining
Final
andComposition
with examples, this really helps a lot.If the class is final, there's a reason for, composition pattern is not a workaround to weaken/break classes design.
With composition you are using the object exactly as intended, not sure how it could weaken or break the class design.
He stated "..is extend the class by using composition"
That's not extending anything.
The reason of this post is so basic (shouldn't even exist), to include a misconception like that
I think what he means is that you can extend its functionality by composition.
I don't think the post shouldn't exist, at least one person appreciated it...
In general basic content is useful for beginners, we're not all at the same stage in our careers or paths.
love the scorpion's reference
Plus you get to implement Effective Java Item 18: "Favor Composition Over Inheritance"
the Substitution principle is also very useful in practice, so Itβs a nuisance if the original authors make a class final but donβt provide an interface for an alternate implementation to conform to.