composition vs inheritance code example

Example 1: inheritance vs composition

Inheritance should only be used when:

  Both classes are in the same logical domain
  The subclass is a proper subtype of the superclass
  The superclass’s implementation is necessary or appropriate for the subclass
  The enhancements made by the subclass are primarily additive.
  There are times when all of these things converge:
  Higher-level domain modeling
  Frameworks and framework extensions
  Differential programming

If you’re not doing any of these things, you probably won’t need class inheritance very often. 
The “preference” for composition is not a matter of “better”, it’s a question of “most appropriate” for your needs, in a specific context.

Hopefully these guidelines will help you out?

Example 2: Which type of inheritance must be used so that the resultant is hybrid?

Which type of inheritance must be used so that the resultant is hybrid?
Explanation: The use of any specific type is not necessary. 
Though the final structure should not be the same, 
it should represent more than one type of inheritance if class diagram is drawn. 8.

Example 3: types of inheritance

//Base Class
class A 
{
 public void fooA()
 {
 //TO DO:
 }
}

//Base Class
class B
{
 public void fooB()
 {
 //TO DO:
 }
}

//Derived Class
class C : A, B
{
 public void fooC()
 {
 //TO DO:
 }
}

Example 4: inheritance programmiz

class Animal {
  // methods and fields
}

// use of extends keyword
// to perform inheritance
class Dog extends Animal {

  // methods and fields of Animal
  // methods and fields of Dog
}

Tags:

Cpp Example