OOPS concept inheritace vs aggregation

Dinesh Pun
Dinesh Pun
8 Points
4 Posts

I have read that code re-usability can be achieve through inheritance. Can't same functionality achieve through Aggregation by creating its object on same class then why we use inheritance?

Views: 8183
Total Answered: 1
Total Marked As Answer: 1
Posted On: 20-Oct-2015 08:51

Share:   fb twitter linkedin
Answers
Rahul Maurya
Rahul M...
Moderator
1172 Points
211 Posts
         

Hi Dinesh pun,

Inheritance and Aggregation are used for code re-usability. But both have slightly different purpose of usability. It's depend on you which one better to use.

Inheritance is 'is a' relationship while Aggregation is 'has a' relationship base usage.

For example,  i) suppose you have Wheel class

public class Wheel
//members 
//methods

and want to use in Car class then you don't have Car extend Wheel. Car has wheels. In this case you have to use aggregation as:  

public class Car
Wheel wheel; 
    // other memebers

ii) suppose you have Vehicle class then you can inherit to new class Car as Car is a vehicle: 

public class Vehicle
//members 
//methods
}
 
public class Car : Vehicle
// inherits Vehicle properties and methods
Posted On: 22-Oct-2015 00:46
 Log In to Chat