Inheritance Vs Composition

Inheritance and Composition both used for code reuse. Inheritance express the ‘is a’ relation and ‘has a’ relation expressed with composition. Both composition and inheritance allow we to place sub-object inside wer new class, composition explicitly does this whereas inheritance does it implicitly.

Composite is generally used when we want the feature of an existing class inside our new class, but not its interface. We embed a class as an object so that we can use it to implement functionality in our new class.

class A
int a;
void dis1()
class B extends A
//Use of inheritance, using extends keyword
void dis2()
class CompoInh
public static void main(String [] args)
//Use of Composition, creating object of another class
B obj= new B();

When we inherit, we take an existing class and make a special version of it. We state inherit by giving the name of the class as usual, but before that opening brace of the class body, put the keyword extends followed by the name of the base class. When we do this, we will automatically get all fields and methods in the base class.

Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

%d bloggers like this: