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

Programming & Frameworks

Topics Covered
  • C Programming and Data Structures (16 Blogs)
  • Comprehensive Java Course (5 Blogs)
  • Java/J2EE and SOA (346 Blogs)
  • Spring Framework (8 Blogs)
SEE MORE

What is Association in Java and why do you need it?

Last updated on Nov 29,2022 52.5K Views

9 / 14 Blog from Java OOPS

How do you establish a connection between two classes when you are writing a Java Program? It’s simple. You can make use of a concept called association. Sounds interesting right? In this article, let’s check out the Association in Java in detail.

The topics discussed in this article are:

What is the Association?

Association in Java is a connection or relation between two separate classes that are set up through their objects. Association relationship indicates how objects know each other and how they are using each other’s functionality. It can be one-to-one, one-to-many, many-to-one and many-to-many.

Association in Java - Edureka

  • For example, a person can have only one passport. That is a “one-to-one” relationship.  
  • If we talk about the association between a Bank and Employee, a bank can have many employees, So it is a “one-to-many” relationship.
  • Similarly, every city exists in exactly one state, but a state can have many cities, which is a “many-to-one” relationship.
  • Lastly, if we talk about the association between a teacher and a student, multiple students can be associated with a single teacher and a single student can also be associated with multiple teachers but both can be created or deleted independently. This is a “many-to-many” relationship.

Let’s understand about Association with an example. 

package MyPackage;
import java.util.*; 

class CityClass {
	 
    private String cityName;
 
    public String getCityName() {
        return cityName;
    }
 
    public void setCityName(String cityName) {
        this.cityName = cityName;
    }
    @Override
    public String toString() {
        return cityName;
    }
}

class State {
	 
    private String stateName;
    
    List<CityClass> citys;
 
    public String getStateName() {
        return stateName;
    }
 
    public void setStateName(String stateName) {
        this.stateName = stateName;
    }
    public List<CityClass> getCities() {
        return citys;
    }
    public void setState(List<CityClass> citys) {
        this.citys = citys;
    }
    
}

public class AssociationExample {

	  public static void main(String[] args) {
	        State state = new State();
	        state.setStateName("California");
	        
	        
	       CityClass city = new CityClass();
	        city.setCityName("Los Angeles");
	        CityClass city2 = new CityClass();
	        city2.setCityName("San Diago");
	        
	        List<CityClass> empList = new ArrayList<CityClass>();
	        empList.add(city);
	        empList.add(city2);
	        
	        
	        state.setState(empList);
	        
	        
	        System.out.println(state.getCities()+" are cities in the state "+
	                state.getStateName());
	    }
	 

}

Output:

[Los Angeles, San Diago] are cities in the state California

As you can see, in this example program there are two classes, namely, states and cities. These two separate classes are associated through their Objects. Moreover, every city exists in exactly one state, but a state can have many cities, hence the term “many-to-one” relationship. Importantly, the association in Java has two special forms. Let’s check them out.

Two Forms of Association

Composition and Aggregation are the two special forms of association. Let’s check them out with the help of an example.

Association - Association in Java - Edureka

Composition

It is a “belongs-to” type of association. It simply means that one of the objects is a logically larger structure, which contains the other object. In other words, it’s part or member of the larger object. Alternatively, it is often called a “has-a” relationship (as opposed to an “is-a” relationship, which is inheritance). 

For example, a building has a room, or in other words, a room belongs to a building. Composition is a strong kind of “has-a” relationship because the objects’ lifecycles are tied. It means that if we destroy the owner object, its members also will be destroyed with it. For example, if the building is destroyed the room is destroyed as well in our previous example. But, note that doesn’t mean, that the containing object can’t exist without any of its parts. For example, if we tear down all the rooms inside a building, the building will still exist.

Aggregation 

Aggregation is also a “has-a” relationship, but, what distinguishes it from composition, is that the lifecycles of the objects are not tied. Both the entries can survive individually which means ending one entity will not affect the other entity. Both of them can exist independently of each other. Therefore, it is often referred to as week association. 

Let’s take the example of a player and a team. A player who is a part of the team can exist even when the team ceases to exist. The main reason why you need Aggregation is to maintain code reusability. 

This brings us to the end of this article where we have learned about Association in Java. If you’re just beginning, then watch at this Java Tutorial to Understand the Fundamental Java Concepts.

If you found this article on “Association in Java” relevant, check out the Edureka’s Java Certification Training, a trusted online learning company with a network of more than 250,000 satisfied learners spread across the globe. If you come across any questions, feel free to ask all your questions in the comments section of “Association in Java” and our team will be glad to answer.

Upcoming Batches For Java Course Online
Course NameDateDetails
Java Course Online

Class Starts on 12th October,2024

12th October

SAT&SUN (Weekend Batch)
View Details
Java Course Online

Class Starts on 14th December,2024

14th December

SAT&SUN (Weekend Batch)
View Details
Comments
0 Comments

Join the discussion

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.

image not found!
image not found!

What is Association in Java and why do you need it?

edureka.co