Friday, 15 June 2018

Inheritance vs Composition in java


They are absolutely different. Inheritance is an "is-a" relationship. Composition is a "has-a".


In the composition approach, the subclass becomes the "front-end class," and the superclass becomes the "back-end class." With inheritance, a subclass automatically inherits an implemenation of any non-private superclass method that it doesn't override. With composition, by contrast, the front-end class must explicitly invoke a corresponding method in the back-end class from its own implementation of the method. This explicit call is sometimes called "forwarding" or "delegating" the method invocation to the back-end object.

The composition approach to code reuse provides stronger encapsulation than inheritance, because a change to a back-end class needn't break any code that relies only on the front-end class. 

Inheritance Example:
class Fruit {

// Return int number of pieces of peel that // resulted from the peeling activity. public int peel() {
System.out.println("Peeling is appealing."); return 1; } }
class Apple extends Fruit { }
class Example1 {
public static void main(String[] args) {
Apple apple = new Apple(); int pieces = apple.peel(); } }

if we want to change return type to peel() then it will effect to main method also so solution is composition as below:

Composition Example:
class Fruit {

// Return int number of pieces of peel that // resulted from the peeling activity. public int peel() {
System.out.println("Peeling is appealing."); return 1; } }
class Apple {
private Fruit fruit = new Fruit();
public int peel() { return fruit.peel(); } }
class Example2 {
public static void main(String[] args) {
Apple apple = new Apple(); int pieces = apple.peel(); } }

ref: https://www.javaworld.com/article/2076814/core-java/inheritance-versus-composition--which-one-should-you-choose-.html

No comments:

Post a Comment

links for Data Structure

  1) 𝐁𝐞𝐜𝐨𝐦𝐞 𝐌𝐚𝐬𝐭𝐞𝐫 𝐢𝐧 𝐋𝐢𝐧𝐤𝐞𝐝 𝐋𝐢𝐬𝐭:  https://lnkd.in/gXQux4zj 2) 𝐀𝐥𝐥 𝐭𝐲𝐩𝐞𝐬 𝐨𝐟 𝐓𝐫𝐞𝐞 𝐓𝐫𝐚𝐯𝐞𝐫𝐬𝐚𝐥𝐬...