Sobes.tech
Middle

Where is it better to apply inheritance and association in programming?

sobes.tech AI

Answer from AI

Inheritance is used when there is an "is-a" relationship between classes. It is used for code reuse and establishing class hierarchies. Example: Cat inherits from Animal.

Association is used when there is a "has-a" or "uses-a" relationship between classes. It is a weaker relationship than inheritance. It is used to establish connections between objects. Association can be:

  • Aggregation: The "whole" consists of "parts", but "parts" can exist independently. Example: Library has Books. Books can exist outside the library.
  • Composition: The "whole" fully controls the lifecycle of the "parts". "Parts" cannot exist without the "whole". Example: Room has a Wall. The wall cannot exist without the room.

Here are code examples:

// Inheritance
public class Animal {
    public void eat() {
        System.out.println("Animal eats");
    }
}

public class Cat extends Animal {
    public void purr() {
        System.out.println("Cat purrs");
    }
}
// Aggregation
import java.util.List;
import java.util.ArrayList;

public class Book {
    private String title;

    public Book(String title) {
        this.title = title;
    }

    public String getTitle() {
        return title;
    }
}

public class Library {
    private List<Book> books;

    public Library() {
        this.books = new ArrayList<>();
    }

    public void addBook(Book book) {
        this.books.add(book);
    }

    public List<Book> getBooks() {
        return books;
    }
}
// Composition
public class Wall {
    private String material;

    public Wall(String material) {
        this.material = material;
    }

    public String getMaterial() {
        return material;
    }
}

public class Room {
    private Wall wall; // Composition

    public Room(String wallMaterial) {
        this.wall = new Wall(wallMaterial);
    }

    public Wall getWall() {
        return wall;
    }
}

Overall, it is preferable to use association (especially composition) instead of inheritance when possible. This promotes better flexibility and weaker coupling between classes. Excessive use of inheritance can lead to rigid hierarchies.