Learn different aspects of IS-A Vs HAS-A Relationship in Java. IS-A (Inheritance) relationship and HAS-A (composition) relationship play a vital role in design consideration, design principles.
1. Overview of IS-A Vs HAS-A Relationship in Java
These two IS-A Vs HAS-A Relationship mostly asked from experience developer to check whether he/she knows basics of design consideration or not. In the object-oriented world, re-use is the basic concept and technique either via IS-A (inheritance) or HAS-A ( composition) relationship.
The fundamental of IS-A is referring to inheritance, it means when inheriting anything from the superclass, you can say IS-A applies. For e.g. IS-A means “SUVCar is a type of Car”, it means, SUVCar.java inherits properties from Car.java (either by extends or implements keyword).
Has-a means “Car has Engine”, and strongly associated, it means Engine object is composed inside the class Car.
2. What is IS-A Relationship?
The fundamental of IS-A is referring to inheritance, it means when inheritance is applied you can say IS-A applies. e.g.
in the real-life world, SUVCar is a Car, the example as follows.
Example of java class
Public class SUVCar extends Car { run(){} } class Car { start() {} stop() {} }
Here , SUVCar
IS-A CAR
, because SUVCar
inherits by extending the Car
class.
3. What is HAS-A Relationship?
The fundamental of HAS-A is referring to composition, it means when association (aggregation or composition) is applied, you can say HAS-A applies. e.g.
Example of java class
public class Car { private Engine engine; start() {} } class Engine { // for brevity an simplicity I put only 2 methods putOil() {} String getEngineNo() {} }
here, we can say, Car has-a Engine, because Engine is composed inside the Car class.
4. Reference
IS-A vs HAS-A Relationship
I hope you enjoyed this post about IS-A vs HAS-A Relationship in Java, and you can visit Core Java tutorial for more blog post.
Your suggestions or comments are welcome to improve this post. Happy Learning! 🙂