They are absolutely different. Inheritance is an "is-a" & Composition is a "has-a" relationship.
Note how the parent is not created until a call is made to the
createParent.
In inheritance the superclass is created when the subclass is created.
In Composition, the object is created when the coder wants it to. This is inheritance, when the Child class is created the parent is
created because the child inherits from parent.
class Parent {
//Some code
}
class Child : Parent{
//Some code
}
This is composition, the object is not created when the child class is
created, instead it is created whenever it is need.
class Parent{
//Some code
}
class Child{
private Parent
parent = new Parent();
//Some code
}
In this case, the Parent class is also created when the Child class is
created. Below is another example of Composition without the object being
created when the child class is created
class Parent{
//Some code
}
class Child{
private Parent
parent;
public Child()
{
}
public void
createParent()
{
parent = new Parent();
}
}
No comments:
Post a Comment