Composition vs Inheritance (Need a good example)

  • Inheritance: IS-A
  • Composition: HAS-A
  • The problem with inheritance is that encourages you to go predict the future…
  • Always favor composition over inheritance
  • Example:
Robot
	.drive()
		CleaningRobot
			.clean()
		MurderRobot
			.kill()
Animal
	.eat()
		Dog
			.bark()
		Cat
			.meaow();


Now the requirement is to have MurderRobotDog which ONLY can:
.drive()
.kill();
.bark();

Hence it becomes problematic to fit it into above inheritance picture properly...

Hence we can do composition, which says:
dog = eater + barker
cat = eater + meower
cleaningRobot = driver + cleaner
murderRobot = driver + killer
murderRobotDog = driver + killer + barker

*********** Always favor composition over inheritance ***********************

Inheritance

  • Powerful but can lead to inflexible designs
  • All classes inherit the same behavior

Composition

  • We can still “inherit” behavior
  • We can make dynamic runtime decisions
  • We can add new behavior without altering existing code
  • We can include behaviors not considered by the creator

Java Example??