Difference between IS-A and HAS-A
IS-A Relationship
The IS-A relationship in Java represents inheritance. It means that a class (subclass) is a type of another class (superclass).
Key Points:
- Inheritance: Established using the `extends` keyword.
- Polymorphism: Subclass objects can be treated as superclass objects.
- Reusability: Subclass inherits fields and methods from the superclass.
- Hierarchy: Reflects a hierarchical relationship.
Example:
Example
```java
// Superclass
class Animal {
void eat() {
System.out.println("This animal eats food.");
}
}
// Subclass
class Dog extends Animal {
void bark() {
System.out.println("The dog barks.");
}
}
public class Test {
public static void main(String[] args) {
Dog myDog = new Dog();
myDog.eat(); // IS-A relationship: Dog IS-A Animal
myDog.bark();
}
}
```
HAS-A Relationship
The HAS-A relationship in Java represents composition. It means that a class contains a reference to another class as a member, indicating ownership.
Key Points:
- Composition: Established by including instances of other classes as fields.
- Encapsulation: Promotes encapsulation and modular design.
- Reusability: Builds complex types from simpler, reusable components.
- Association: Reflects an association between classes.
Example:
Example
```java
// Class representing an Engine
class Engine {
void start() {
System.out.println("Engine starts.");
}
}
// Class representing a Car
class Car {
// Car HAS-A Engine
private Engine engine;
Car() {
engine = new Engine(); // Composition: Car HAS-A Engine
}
void startCar() {
engine.start(); // Delegating behavior to the Engine
System.out.println("Car starts.");
}
}
public class Test {
public static void main(String[] args) {
Car myCar = new Car();
myCar.startCar(); // HAS-A relationship: Car HAS-A Engine
}
}
```
Summary
IS-A Relationship:
- Keyword: `extends`.
- Hierarchy: Establishes a hierarchy (e.g., Dog IS-A Animal).
- Example: A `Dog` class extends an `Animal` class.
HAS-A Relationship:
- Implementation: Using instance variables.
- Association: Represents a class containing another class (e.g., Car HAS-A Engine).
- Example: A `Car` class has an `Engine` object as a member.
Understanding these relationships helps in designing robust, maintainable, and reusable object-oriented systems in Java.