Java/J2EE and SOA (325 Blogs) Become a Certified Professional
AWS Global Infrastructure

Programming & Frameworks

Topics Covered
  • C Programming and Data Structures (41 Blogs)
  • Comprehensive Java Course (2 Blogs)
  • Java/J2EE and SOA (324 Blogs)
  • Spring Framework (8 Blogs)
SEE MORE

MI-new-launch

myMock Interview Service for Real Tech Jobs

myMock-widget-banner-bg

Everything you need to Know about Has a Relationship in Java

Published on Oct 15,2019 42 Views

MI-new-launch

myMock Interview Service for Real Tech Jobs

myMock-mobile-banner-bg

myMock Interview Service for Real Tech Jobs

  • Mock interview in latest tech domains i.e JAVA, AI, DEVOPS,etc
  • Get interviewed by leading tech experts
  • Real time assessment report and video recording

Has a Relationship in Java and Is a Relationship are two of the most confusing terms. In this article, we will focus on the following parameters:

 

An Introduction to Has a Relationship in Java

Has a relationship in Java is known to be as Composition. It is used for code reusability. Basically, it means that an instance of the one class has a reference to the instance of another class or the other instance of the same class. This relationship helps to minimize the duplication of code as well as the bugs.

A composition is a form of Association. Association is known as the relation between two separate classes that are authorized through their objects. Association can be of the form : 

  1. One-to-one

  2. One-to-many

  3. Many-to-one

  4. Many-to-many

In OOP ( Object Oriented Programming), Object communicates with another object to use all the services and the functionalities provided by that object.

 

Association

Here is an example of the implementation of the Association.

import java.io.*; 
class Bank 
{ 
	private String name; 
	Bank(String name) 
	{ 
            this.name = name; 
} 
	public String getBankName() 
	{ 
		return this.name; 
	} 
} 
class Employee 
{ 
	private String name; 
	Employee(String name) 
	{ 
		this.name = name; 
	} 
	public String getEmployeeName() 
	{ 
		return this.name; 
	} 
} 
class Association 
{ 
	public static void main (String[] args) 
	{ 
		Bank b = new Bank("Axis"); 
		Employee e = new Employee("Himanshi"); 
		System.out.println(e.getEmployeeName() + 
			" is an employee of " + b.getBankName()); 
	} 
}

Output:

has-a-relationship-in-java

 

This is the special form of association where:

  1. This represents Has-a-relationship.

  2. It is known as a unidirectional association ( a one-way relation) For example, the department can have teachers but vice versa is not true and hence, unidirectional in nature.

Now let us talk about Composition 

The composition is the restricted form in which two objects are hugely dependent on each other. When there exists composition between the two entities, the composed cannot lie without another entity.

Here is the example of the library for showing the concept of composition

import java.io.*; 
import java.util.*; 
class Book 
{ 
	public String title; 
	public String author; 
	Book (String title, String author) 
	{ 
		this.title = title; 
		this.author = author; 
	} 
} 
class Library 
{ 
	private final List <Book> books; 
	
	Library (List <Book> books) 
	{ 
		this.books = books; 
	} 
	public List<Book> getTotalBooksInLibrary( )
{ 	
	return books; 
	} 
} 
class edureka
{ 
	public static void main (String[ ] args) 
	{  
		Book b2 = new Book ("Thinking Java", "Brua E"); 
		Book b3 = new Book ("Java: Complete Reference", "Herb S"); 
		
		List <Book> books = new ArrayList <Book>( );  
		books.add (b2); 
		books.add (b3); 
		
		Library library = new Library (books); 
		
		List<Book> bks = library.getTotalBooksInLibrary ( ); 
		for (Book bk : bks)
{ 	
      System.out.println ("Title : " + bk.title + " and "+" Author : " + bk.author); 
		} 
	} 
}

Output:

has-a-relationship-2

 

One of the main advantages of OOPS is we can reuse the code. There are two ways by which we can reuse the code is an implementation of inheritance or by the object composition.

 

Comparing Composition and Inheritance: Relationship

  • It is easier in composition to change the class than in inheritance.

  • Inheritance is the static binding while the composition is the dynamic binding.

  • Class inheritance is defined at the compile-time whereas the object composition is defined at the run-time.

  • In object composition, the internal details are not supposed to expose to each other and they interact by their public interfaces whereas, In Inheritance, it exposes both the public and the protected members of the base class.

  • In Composition, Access can be restricted whereas, In Object composition, there is no access control.

  • In Inheritance, it breaks encapsulation by exposing a subclass to the details of its parent’s implementation whereas, In Object Composition, it does not break encapsulation because objects are accessed completely through their interfaces.

  • In Inheritance, it provides the code reusability whereas, In Object Composition, It allows representing the associations.

 

Example 1:

class Operation
{
 int square (int n)
{
  return n*n;
 }
}
class Circle
{
 Operation op;
//aggregation
 double pi=3.14; 
 double area (int radius)
{
   op =new Operation( );
   int rsquare = op.square (radius);
//code reusability (i.e. delegates the method call).
  return pi*rsquare;
 }
 public static void main (String args[ ])
{
   Circle c=new Circle( );
   double result=c.area (5);
System.out.println (result);
 }
}

Output:

OP-has-a-relatioship

 

Example 2:

class House {
Kitchen k = new Kitchen ( );
//more code for house class
}
Class Kitchen
{
//code of kitchen class
}

If the house gets destroyed, the kitchen will also get destroyed. This is known as the composition when two entities are dependent on each other. The reference class (Kitchen) could not exist without the container class (House).

With this, we come to an end of this Has A Relationship In Java article. Basically, In composition, a class can reuse the functionality of the class by creating a reference to the object of class which it wants to reuse. It is known as the special case of aggregation.

Check out the Java training by Edureka, a trusted online learning company with a network of more than 250,000 satisfied learners spread across the globe. Edureka’s Java J2EE and SOA training and certification course is designed for students and professionals who want to be a Java Developer.

Got a question for us? Please mention it in the comments section of this “Has a Relationship in Java”blog and we will get back to you as soon as possible.

Comments
0 Comments

Browse Categories

webinar REGISTER FOR FREE WEBINAR
REGISTER NOW
webinar_success Thank you for registering Join Edureka Meetup community for 100+ Free Webinars each month JOIN MEETUP GROUP

Subscribe to our Newsletter, and get personalized recommendations.