Code360 powered by Coding Ninjas X Naukri.com. Code360 powered by Coding Ninjas X Naukri.com
Table of contents
1.
Introduction
2.
What is Has-a relationship
2.1.
Implementation
2.2.
Example
3.
Comparing Composition and Inheritance: Relationship
3.1.
Inheritance:
3.2.
Composition:
4.
How to Decide which Type of Relation We Need
4.1.
Understand the Relationship:
4.2.
Consider Flexibility and Maintenance:
4.3.
Assess Reusability Needs:
4.4.
Evaluate Coupling:
4.5.
Think About Extensibility:
4.6.
Specificity of Use Cases:
5.
Types of Has-A-Relationship
6.
Frequently Asked Questions
6.1.
What is the difference between is a and has a relationship in Java?
6.2.
How do you create a has a relationship in Java?
6.3.
Is a has a relationship database?
6.4.
Is a VS has a relationship in Java example?
7.
Conclusion
Last Updated: Mar 27, 2024
Easy

Has-A Relationship in Java

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.
     
Has-a Relationship


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..

 

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.

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.

Do upvote our blog to help other ninjas grow. Happy Coding!”

Live masterclass