Table of contents
1.
Introduction
2.
What is Has-a relationship
2.1.
Implementation
2.2.
Example
3.
Why Is It Important in Object-Oriented Programming?
4.
Comparing Composition and Inheritance: Relationship
4.1.
Inheritance:
4.2.
Composition:
5.
How to Decide which Type of Relation We Need
5.1.
Understand the Relationship:
5.2.
Consider Flexibility and Maintenance:
5.3.
Assess Reusability Needs:
5.4.
Evaluate Coupling:
5.5.
Think About Extensibility:
5.6.
Specificity of Use Cases:
6.
Types of Has-A-Relationship
7.
Has-A vs Is-A Relationship
7.1.
Key Differences Between Has-A and Is-A
7.2.
When to Use Has-A Over Is-A?
8.
Real-World Analogy
9.
Understanding Has-A with Real-Life Examples
10.
Benefits of Has-A Relationship
11.
Best Practices for Has-A Relationship in Java
11.1.
How to Design Clean Has-A Relationships
11.2.
Tips for Class Composition
11.3.
Avoiding Common Mistakes
12.
Common Use Cases of Has-A Relationship
13.
Frequently Asked Questions
13.1.
What is the difference between is a and has a relationship in Java?
13.2.
How do you create a has a relationship in Java?
13.3.
Is a has a relationship database?
13.4.
Is a VS has a relationship in Java example?
14.
Conclusion
Last Updated: Jul 1, 2025
Easy

Has-A Relationship in Java

Career growth poll
Do you think IIT Guwahati certified course can help you in your career?

Introduction

Java is an object-oriented programming language that supports inheritance. Inheritance is the ability to inherit the features and functionalities from another class. It supports the reuse of the same code. It allows the programmer to define a class in terms of another class. A relationship in Java means different relations between two or more classes. In Java, we can have a has-a relationship between classes, otherwise known as composition. A composition is a form of association, where an association is a relation between two classes that is established using their objects. 

Has-A Relationship in Java

What is Has-a relationship

In Java, has-a relationship implies that an example of one class has a reference to an occasion of another class. There is no watchword to implement has-a relationship in Java. Has-a is a special form of association. Some of the important points of a has-a relationship are : 

  • It is a one-way relationship or a unidirectional association.
  • Both entries can survive independently in aggregation, which means ending one entity will not affect the other entity.
 flowchart shows that the class Ktm has-a an engine


The above flowchart shows that the class Ktm has-a an engine.

Implementation

  1. The class Bike has a few instance variables and methods.
  2. Ktm is a type of Bike that extends the Bike class that shows Ktm is a Bike. Ktm also uses an Engine’s method, engine_kill, using composition, which shows that Ktm has an Engine.
  3. The Engine class has two methods naming engine_on() and engine_kill(), used by the Ktm class.

Example

// Parent class
public class Bike {

    private String color;
    private int topSpeed;
  
    // Main driver method
    public static void main(String[] args)
    {
        // Creating an object of Bike class
        Bike Ktm390 = new Bike();

        Ktm390.setColor("ORANGE");
        Ktm390.setTopSpeed(179);
  
        // Calling bikeInfo() over object of Bike class
        Ktm390.bikeInfo();
  
        // Creating an object of KTM class
        KTM ktm = new KTM();
        ktm.KTM_DEMO();
    }
  
    // Methods implementation
    // set the maximum speed of bike
    public void setTopSpeed(int maxSpeed)
    {
        this.topSpeed = maxSpeed;
    }
    // set the color of bike
    public void setColor(String color)
    {
        this.color = color;
    }
    // print bike information
    public void bikeInfo()
    {
        System.out.println("Bike Color= " + color
                          + " Top Speed= " + topSpeed);
    }
}
  
// Child class
class KTM extends Bike {
    public void KTM_DEMO()
    {
        // Creating an object of Engine type
        // using engine_kill() method
        // KTM_Engine is name of an object
        Engine KTM_Engine = new Engine();
        KTM_Engine.engine_on();
        KTM_Engine.engine_kill();
    }
}

class Engine {
    // To start the engine
    public void engine_on()
    {
        // Print when engine is turned on
        System.out.println("Ignition On..");
    }
    // To stop the engine
    public void engine_kill()
    {
        // Print when engine is turned off
        System.out.println("Ignition killed..");
    }
}


Output

Bike Color= ORANGE Top Speed= 179
Ignition On..
Ignition killed..

Why Is It Important in Object-Oriented Programming?

The Has-A relationship (also known as object composition) is a fundamental concept in Object-Oriented Programming (OOP). It allows one object to contain or reference another, modeling real-world relationships like “a car has an engine” or “a library has books.”

Unlike inheritance, which creates rigid hierarchies, composition offers greater flexibility and modularity. It allows developers to build complex systems by combining smaller, reusable components.

Here are four key reasons why Has-A relationships matter in OOP:

  • Modularity: Code is easier to break into smaller, manageable pieces.
     
  • Flexibility: You can change components without affecting other parts.
     
  • Abstraction: Internals of composed objects can be hidden, promoting clean interfaces.
     
  • Real-World Mapping: Mirrors natural relationships, making system design intuitive.
     

In many Java applications, composition is preferred over inheritance, especially when objects interact without needing a parent-child relationship.

Comparing Composition and Inheritance: Relationship

Composition and inheritance are two fundamental concepts in object-oriented programming, each with its distinct way of structuring relationships between classes. While inheritance establishes a direct lineage, composition assembles objects to create complex entities.

Inheritance:

  • Represents an "is-a" relationship.
  • Used for code reuse and establishing a hierarchy between classes.
  • Allows a subclass to inherit properties and behaviors from a parent class.
  • Can lead to tight coupling and difficulty in modifying individual classes.
  • Examples: A Dog class inheriting from an Animal class, indicating a Dog "is an" Animal.
     

Composition:

  • Embodies a "has-a" relationship.
  • Involves building complex objects from simpler ones.
  • Provides greater flexibility, allowing modification of composed objects without affecting others.
  • Encourages loose coupling, making the system more modular and easier to change.
  • Examples: A Car class having an Engine object, indicating a Car "has an" Engine.

How to Decide which Type of Relation We Need

Understand the Relationship:

  1. Analyze if the classes share an "is-a" (inheritance) or "has-a" (composition) relationship.
  2. For a natural hierarchical relationship, use inheritance.
  3. For a relationship where one class uses the functionality of another class, consider composition.

Consider Flexibility and Maintenance:

  1. If you need high flexibility and ease of maintenance, composition is often a better choice.
  2. Composition allows for more modular code, easier to modify without affecting other parts.

Assess Reusability Needs:

  1. Use inheritance for situations where you want to extend the functionality of existing classes across a hierarchy.
  2. When reusability of code in a hierarchical structure is crucial, inheritance can be effective.

Evaluate Coupling:

  1. Composition reduces coupling, making it preferable for classes that should not be tightly bound.
  2. Inheritance can lead to tight coupling, which may complicate future changes.

Think About Extensibility:

  1. If you need to frequently extend or modify functionalities, composition offers better extensibility.
  2. Inheritance can be less flexible in terms of extending functionalities, especially in deep hierarchies.

Specificity of Use Cases:

  1. Inheritance is useful when subclassing to create specific types of a general class.
  2. Composition is suited for combining different functionalities or behaviors dynamically.

Types of Has-A-Relationship

In object-oriented programming, there are two primary types of "Has-A" relationships: Aggregation and Composition. Aggregation is a form of association where two objects have their own life cycle, but there exists a ownership relationship between them. It is characterized by weak bonding. For instance, a library and students represent this relationship - students can study without the library, but the library serves no purpose without students. On the other hand, Composition is a stricter form of aggregation where the contained object cannot exist independently of the container. An example is a car and its engine - a car cannot function without its engine, and the engine is typically useless without the car. This form of relationship indicates a strong bonding between the classes.

Certainly! Here's a well-structured and SEO-optimized section for Has-A vs Is-A Relationship in Java:

Has-A vs Is-A Relationship

Key Differences Between Has-A and Is-A

  • In Object-Oriented Programming (OOP), understanding the difference between Has-A and Is-A relationships is crucial for designing clean, maintainable Java applications.
     
  • Is-A represents inheritance. For example, a Car is-a Vehicle means the Car class inherits from Vehicle.
     
  • Has-A represents composition. For example, a Car has-a Engine means the Car class contains an Engine object.
     

Comparison:

FeatureHas-A (Composition)Is-A (Inheritance)
DefinitionObject contains another objectObject is a subtype of another object
Relationship TypeLoose couplingTight coupling
FlexibilityHigh – components are replaceableLess flexible
ReusabilityEncourages reuse through componentsReuse via shared parent class
Real-World ExampleCar has-a EngineCar is-a Vehicle

When to Use Has-A Over Is-A?

Has-A should be used when:

  • Modular Design is Needed – Prefer composition when objects need to be built from reusable parts (e.g., Library has Books).
     
  • Low Coupling Is Desired – Changing one component won’t affect the others.
     
  • Behavior Needs to Change Dynamically – Composition allows changing behavior at runtime more easily than inheritance.
     

Avoid overusing Is-A, as deep inheritance chains can lead to rigid, hard-to-maintain code. In modern Java development, favoring composition over inheritance is a widely accepted best practice.

Real-World Analogy

To understand the Has-A relationship in Java, think about a Car and its Engine. A Car has-a Engine, but it is not an engine itself. This simple relationship mirrors real-world interactions, where one object contains or uses another to perform its tasks. Just like a Library has Books or a Computer has a Keyboard, these examples help us model real-world scenarios effectively in object-oriented programming.

Understanding Has-A with Real-Life Examples

In Java, Has-A represents object composition, where a class includes instances of other classes as fields.

Car has-a Engine

class Engine {}
class Car {
    Engine engine = new Engine();
}
You can also try this code with Online Java Compiler
Run Code

Student has-a Address

class Address {}
class Student {
    Address address;
}
You can also try this code with Online Java Compiler
Run Code

Library has-a Book

class Book {}
class Library {
    List<Book> books = new ArrayList<>();
}
You can also try this code with Online Java Compiler
Run Code

These examples show how real-world systems are modeled in Java using class composition to represent object ownership or association.

Benefits of Has-A Relationship

Code Reusability and Modularity
By reusing existing classes (like Engine or Address) in other classes, you avoid code duplication and create modular designs that are easier to test and maintain.
 

Better Abstraction and Flexibility
Classes can focus on their primary behavior and delegate tasks to composed objects, leading to better abstraction. For instance, the Car delegates engine tasks to the Engine class.
 

Loose Coupling for Maintainable Code
Has-A relationships allow replacing parts (like the Engine) without altering the main class. This makes the system more flexible and reduces the impact of future changes.
 

Has-A promotes clean architecture, separation of concerns, and real-world modeling, making your Java applications more robust and scalable.

Best Practices for Has-A Relationship in Java

How to Design Clean Has-A Relationships

  • Use interfaces to inject dependencies and support flexible implementations.
     
  • Always favor composition over inheritance unless a true "Is-A" relationship exists.

Tips for Class Composition

  • Keep the composition meaningful and minimal.
     
  • Inject composed objects through constructors for better testability (Dependency Injection).

Avoiding Common Mistakes

  • Avoid deeply nested compositions that increase complexity.
     
  • Don’t misuse Has-A just to reuse unrelated methods or data—it breaks design principles.
     
  • Following these best practices leads to clean, testable, and extendable code in real-world Java applications.

Common Use Cases of Has-A Relationship

Here are some typical applications of Has-A in Java:

Car has-a Engine

class Car {
    Engine engine = new Engine();
}
You can also try this code with Online Java Compiler
Run Code


Student has-a Address

class Student {
    Address address;
}
You can also try this code with Online Java Compiler
Run Code


Employee has-a Department

class Employee {
    Department dept;
}
You can also try this code with Online Java Compiler
Run Code


These examples show how classes are composed to reflect real-world hierarchies and dependencies, improving code clarity and system design.

Frequently Asked Questions

What is the difference between is a and has a relationship in Java?

In Java, "is-a" signifies inheritance, representing a subclass-superclass relationship, whereas "has-a" denotes composition, indicating that a class contains an instance of another class as a field, reflecting a component-container relationship.

How do you create a has a relationship in Java?

To create a has a relationship in Java, you declare an instance variable in one class of the type of the other class, and then use it to access the methods and properties of the referenced object.

Is a has a relationship database?

No, a has a relationship is not a database. It is a concept used in object-oriented programming, while databases use relationships such as one-to-one, one-to-many, and many-to-many to establish connections between tables and data.

Is a VS has a relationship in Java example?

Yes, a VS (Variable Scope) has a relationship in Java. It defines the accessibility of a variable in different parts of a program and can be controlled using access modifiers.

Conclusion

In this article, we have extensively discussed what has-a relationship is and how we can implement it in Java programming language with examples and their implementation in Visual Studio Code.

We hope that this blog has helped you enhance your knowledge regarding has-a relationship in the Java programming language and if you would like to learn more, check out our articles on what is Multiple Inheritance in Java, what is Hybrid Inheritance in Java, what is hierarchical inheritance in Java.

Live masterclass