Skip to content
geeksforgeeks
  • Tutorials
    • Python
    • Java
    • Data Structures & Algorithms
    • ML & Data Science
    • Interview Corner
    • Programming Languages
    • Web Development
    • CS Subjects
    • DevOps And Linux
    • School Learning
    • Practice Coding Problems
  • Courses
    • DSA to Development
    • Get IBM Certification
    • Newly Launched!
      • Master Django Framework
      • Become AWS Certified
    • For Working Professionals
      • Interview 101: DSA & System Design
      • Data Science Training Program
      • JAVA Backend Development (Live)
      • DevOps Engineering (LIVE)
      • Data Structures & Algorithms in Python
    • For Students
      • Placement Preparation Course
      • Data Science (Live)
      • Data Structure & Algorithm-Self Paced (C++/JAVA)
      • Master Competitive Programming (Live)
      • Full Stack Development with React & Node JS (Live)
    • Full Stack Development
    • Data Science Program
    • All Courses
  • Java Arrays
  • Java Strings
  • Java OOPs
  • Java Collection
  • Java 8 Tutorial
  • Java Multithreading
  • Java Exception Handling
  • Java Programs
  • Java Project
  • Java Collections Interview
  • Java Interview Questions
  • Java MCQs
  • Spring
  • Spring MVC
  • Spring Boot
  • Hibernate
Open In App
Next Article:
What is Has-A-Relation in Java?
Next article icon

What is Has-A-Relation in Java?

Last Updated : 16 Sep, 2024
Comments
Improve
Suggest changes
Like Article
Like
Report

Association is the relation between two separate classes which establishes through their Objects. Composition and Aggregation are the two forms of association. In Java, a Has-A relationship is otherwise called composition. It is additionally utilized for code reusability in Java. In Java, a Has-A relationship essentially implies that an example of one class has a reference to an occasion of another class or another occurrence of a similar class. For instance, a vehicle has a motor, a canine has a tail, etc. In Java, there is no such watchword that executes a Has-A relationship. Yet, we generally utilize new catchphrases to actualize a Has-A relationship in Java.

Has-A-Relation-Java

Has-a is a special form of Association where:

  • It represents the Has-A relationship.
  • It is a unidirectional association i.e. a one-way relationship. For example, here above as shown pulsar motorcycle has an engine but vice-versa is not possible and thus unidirectional in nature.
  • In Aggregation, both the entries can survive individually which means ending one entity will not affect the other entity.

Illustration:

Has-A-Relation-Java-Example

This shows that class Pulsar Has-a an engine. By having a different class for the engine, we don't need to put the whole code that has a place with speed inside the Van class, which makes it conceivable to reuse the Speed class in numerous applications.  

In an Object-Oriented element, the clients don't have to make a big deal about which article is accomplishing the genuine work. To accomplish this, the Van class conceals the execution subtleties from the clients of the Van class. Thus, essentially what happens is the clients would ask the Van class to do a specific activity and the Van class will either accomplish the work without help from anyone else or request that another class play out the activity.

Implementation: Here is the implementation of the same which is as follows: 

  1. Car class has a couple of instance variable and few methods
  2. Maserati is a type of car that extends the Car class that shows Maserati is a Car. Maserati also uses an Engine's method, stop, using composition. So it shows that a Maserati has an Engine.
  3. The Engine class has the two methods start() and stop() that are used by the Maserati class.

Example:

Java
// Java Program to Illustrate has-a relation  // Class1 // Parent class public class Car {      // Instance members of class Car     private String color;     private int maxSpeed;      // Main driver method     public static void main(String[] args)     {         // Creating an object of Car class         Car nano = new Car();          // Assigning car object color         nano.setColor("RED");          // Assigning car object speed         nano.setMaxSpeed(329);          // Calling carInfo() over object of Car class         nano.carInfo();          // Creating an object of Maserati class         Maserati quattroporte = new Maserati();          // Calling MaseratiStartDemo() over         // object of Maserati class         quattroporte.MaseratiStartDemo();     }      // Methods implementation      // Method 1     // To set the maximum speed of car     public void setMaxSpeed(int maxSpeed)     {         // This keyword refers to current object itself         this.maxSpeed = maxSpeed;     }      // Method 2     // To set the color of car     public void setColor(String color)     {         // This keyword refers to current object         this.color = color;     }      // Method 3     // To display car information     public void carInfo()     {         // Print the car information - color and speed         System.out.println("Car Color= " + color                            + " Max Speed= " + maxSpeed);     } }  // Class2 // Child class // Helper class class Maserati extends Car {      // Method in which it is shown     // what happened with the engine of Puslar     public void MaseratiStartDemo()     {         // Creating an object of Engine type         // using stop() method         // Here, MaseratiEngine is name of an object         Engine MaseratiEngine = new Engine();         MaseratiEngine.start();         MaseratiEngine.stop();     } }  // Class 3 // Helper class class Engine {      // Method 1     // To start a engine     public void start()     {         // Print statement when engine starts         System.out.println("Started:");     }      // Method 2     // To stop a engine     public void stop()     {         // Print statement when engine stops         System.out.println("Stopped:");     } } 

Output
Car Color= RED Max Speed= 329 Started: Stopped: 

Next Article
What is Has-A-Relation in Java?

S

swatidubey
Improve
Article Tags :
  • Java
  • Java-Object Oriented
  • java-inheritance
Practice Tags :
  • Java

Similar Reads

    What is Is-A-Relationship in Java?
    A relationship in Java means different relations between two or more classes. For example, if a class Bulb inherits another class Device, then we can say that Bulb is having is-a relationship with Device, which implies Bulb is a device. In Java, we have two types of relationship: Is-A relationship:
    3 min read
    Field equals() method in Java with Examples
    The equals() method of java.lang.reflect.Field is used to compare two field objects. This method compares two field objects and returns true if both objects are equal otherwise false. The two Field objects are considered equal if and only if when they were declared by the same class and have the sam
    3 min read
    Java Relational Operators with Examples
    Operators constitute the basic building block to any programming language. Java too provides many types of operators which can be used according to the need to perform various calculations and functions, be it logical, arithmetic, relational, etc. They are classified based on the functionality they
    10 min read
    Hashtable contains() Method in Java
    The java.util.Hashtable.contains(Object value) method in Java is used to check whether a particular value is being mapped by any keys present in the Hashtable. Syntax: Hash_table.contains(Object value) Parameters: The method accepts one parameter value of object type and refers to the value of the h
    2 min read
    Classes and Objects in Java
    In Java, classes and objects are basic concepts of Object Oriented Programming (OOPs) that are used to represent real-world concepts and entities. The class represents a group of objects having similar properties and behavior, or in other words, we can say that a class is a blueprint for objects, wh
    11 min read
geeksforgeeks-footer-logo
Corporate & Communications Address:
A-143, 7th Floor, Sovereign Corporate Tower, Sector- 136, Noida, Uttar Pradesh (201305)
Registered Address:
K 061, Tower K, Gulshan Vivante Apartment, Sector 137, Noida, Gautam Buddh Nagar, Uttar Pradesh, 201305
GFG App on Play Store GFG App on App Store
Advertise with us
  • Company
  • About Us
  • Legal
  • Privacy Policy
  • In Media
  • Contact Us
  • Advertise with us
  • GFG Corporate Solution
  • Placement Training Program
  • Languages
  • Python
  • Java
  • C++
  • PHP
  • GoLang
  • SQL
  • R Language
  • Android Tutorial
  • Tutorials Archive
  • DSA
  • Data Structures
  • Algorithms
  • DSA for Beginners
  • Basic DSA Problems
  • DSA Roadmap
  • Top 100 DSA Interview Problems
  • DSA Roadmap by Sandeep Jain
  • All Cheat Sheets
  • Data Science & ML
  • Data Science With Python
  • Data Science For Beginner
  • Machine Learning
  • ML Maths
  • Data Visualisation
  • Pandas
  • NumPy
  • NLP
  • Deep Learning
  • Web Technologies
  • HTML
  • CSS
  • JavaScript
  • TypeScript
  • ReactJS
  • NextJS
  • Bootstrap
  • Web Design
  • Python Tutorial
  • Python Programming Examples
  • Python Projects
  • Python Tkinter
  • Python Web Scraping
  • OpenCV Tutorial
  • Python Interview Question
  • Django
  • Computer Science
  • Operating Systems
  • Computer Network
  • Database Management System
  • Software Engineering
  • Digital Logic Design
  • Engineering Maths
  • Software Development
  • Software Testing
  • DevOps
  • Git
  • Linux
  • AWS
  • Docker
  • Kubernetes
  • Azure
  • GCP
  • DevOps Roadmap
  • System Design
  • High Level Design
  • Low Level Design
  • UML Diagrams
  • Interview Guide
  • Design Patterns
  • OOAD
  • System Design Bootcamp
  • Interview Questions
  • Inteview Preparation
  • Competitive Programming
  • Top DS or Algo for CP
  • Company-Wise Recruitment Process
  • Company-Wise Preparation
  • Aptitude Preparation
  • Puzzles
  • School Subjects
  • Mathematics
  • Physics
  • Chemistry
  • Biology
  • Social Science
  • English Grammar
  • Commerce
  • World GK
  • GeeksforGeeks Videos
  • DSA
  • Python
  • Java
  • C++
  • Web Development
  • Data Science
  • CS Subjects
@GeeksforGeeks, Sanchhaya Education Private Limited, All rights reserved
We use cookies to ensure you have the best browsing experience on our website. By using our site, you acknowledge that you have read and understood our Cookie Policy & Privacy Policy
Lightbox
Improvement
Suggest Changes
Help us improve. Share your suggestions to enhance the article. Contribute your expertise and make a difference in the GeeksforGeeks portal.
geeksforgeeks-suggest-icon
Create Improvement
Enhance the article with your expertise. Contribute to the GeeksforGeeks community and help create better learning resources for all.
geeksforgeeks-improvement-icon
Suggest Changes
min 4 words, max Words Limit:1000

Thank You!

Your suggestions are valuable to us.

What kind of Experience do you want to share?

Interview Experiences
Admission Experiences
Career Journeys
Work Experiences
Campus Experiences
Competitive Exam Experiences