-2

I know this has been asked, but is generally explained in context with something else and feels a little complicated.

Inheritance is when classes inherit properties from a super class, correct? What exactly is composition?

Zach Smith
  • 8,458
  • 13
  • 59
  • 133
  • Composition is when a class simply uses instances of other classes to achieve behavior. – Daniel Lyons Nov 04 '14 at 18:25
  • "I know this has been asked": You mean this question? [Prefer composition over inheritance?](http://stackoverflow.com/q/49002/2596334) – Scott Solmer Nov 04 '14 at 18:31
  • What exactly don't you understand about composition? – Scott Solmer Nov 04 '14 at 18:32
  • How would you access the encapsulated classes? Does the class provide methods for accessing encapsulated classes? I've just read that white-box reuse is more complex complex because it involves knowing the inner working of the class.. but to me it would seem that black box reuse is more difficult because you would have to design far more generic functionality... – Zach Smith Nov 04 '14 at 18:41
  • if you are inheriting from generic classes, wouldn't it be much easier to just have all subclasses have access to the main classes methods? – Zach Smith Nov 04 '14 at 18:46
  • what happens if you inherit from a class composition? – Zach Smith Nov 04 '14 at 18:46
  • If C uses B internally and D inherits from C, then D "is a" C (inheritance) but presumably much of the behavior is supplied by composition because C "has a" B. D does transitively "have a" B but unless the B is `protected` (meaning D can see it) it would not be considered composition. Inheritance is worse than composition, so it doesn't wash off as easily as composition. – Daniel Lyons Nov 05 '14 at 06:59
  • 1
    Black box reuse requires somewhat more effort, but the effort is repaid in the long run by having obvious dependencies, and having those be dependencies on _interfaces_ rather than _implementations_. Inheritance couples the subclass to the implementation of the parent class which makes change more difficult. Look at any long-lived OOP library and you will see inheritance is frequently replaced with composition but almost never the other way around. – Daniel Lyons Nov 05 '14 at 07:03

2 Answers2

1
Class Bird;
Class Duck;
Class Wing;

Duck "is a" bird <- inheritance.

Duck "has a" wing <- composition.

Hopefully it has two wings.

daveross1212
  • 91
  • 2
  • 1
0

Inheritance is as you said when classes inherited properties and methods from parent class. Compasition is when a class has an instance of another class.

public class Person{
   private Car car;
}

Person class is related to Car class by compositon because it holds an instance of Car class

Salih Erikci
  • 5,076
  • 12
  • 39
  • 69