Difference between IS-A relationship and Has-A relationship.
- It isÂ known as an inheritance
- The main advantage of IS-A relationship is code reusability.
- By using extends keyword we can implement IS-A relationship.
- Whatever method parent has by-default available to the child and hence on the child reference we can call both parent and child method.
- Whatever method child has by-default not available to parent and hence parent reference we can’t call child specific methods.
- Parent reference can be used to hold child object but by using that reference we can’t call child specific method but we can call the method present in the parent class.
- Parent reference can be used to hold child object but child reference can’t be used to hold parent object.
- Total Java API is implemented based on inheritance concept.
- The most common method which is applicable for any Java object is defined in object class and hence every class in java is the child class of object either directly or indirectly so that object class method by default available to every java class without re-writing due to this object class access as root for all java classes.
- Throwable class defines the most common method which is required for every exception and error classes. Hence this class act as a root class for Java exception hierarchy.
- Inheritance (is-a) relationships are derived from child classes that inherit attributes and methods from their parent class.
IS-AÂ relationship (is-a kind of)Â is basically a generalization-specialization relationship in oops. A human being is a kind of mammal. A mammal is a kind of animal. It is a relationship between a special class and a general class. The special class inherits the properties of the general class.
- Has-A relationship is also known as Composition and Aggregation.
- There is no specific keyword to implement HAS-A relation but most of the time we are depending on the new keyword.
- Composition (has-a) relationships are classes whose attributes are comprised of other classes.
- the has-a relationship is association relationship. For example ” A student has a college in which he presently studies”. A person has a name.
- Composition is dynamic binding (run-time binding) while Inheritance is static binding (compile-time binding)
- Don’t use inheritance just to get code reuseÂ If all you really want is to reuse code and there is no is-a relationship in sight, use composition.
- Don’t use inheritance just to get at polymorphismÂ If all you really want is a polymorphism, but there is no natural is-a relationship, use composition with interfaces.
- The main advantage of Has-A relationship is reusability of the code. Example..
engine e=new engine();
–>Â Car HAS-A engine reference
\\engineÂ specific functionality
- Note:-Â If we want total functionality of a class automatically then we should go for IS-A relationship.If we want part of functionality then we should go for Has-A Relationship.