---
title: "What is composition in Java?"  
description: "What is composition in Java?"  
author: "Siris Jain"  
published: 2017-11-14  
canonical: https://answers.mindstick.com/qa/30604/what-is-composition-in-java  
category: "programming"  
tags: ["java programming"]  
reading_time: 1 minute  

---

# What is composition in Java?

What is [composition](https://www.mindstick.com/forum/23021/aggregation-and-composition-in-java) in [Java](https://www.mindstick.com/articles/12086/arrays-in-java-non-rectangular-arrays-part-5)?

## Answers

### Answer by Arti Mishra

## "Composition in Java"

The composition is a technique that is used to **implement has-a relationship between object.** And for **reusing the code**, you can use **java inheritance or object composition.**

In Java, a composition is **achieved by using instance variables** that pointed to other objects. '\
**Employee.java** public class Employee { private String name; private long salary; private int id; public String getName() { return name; } public void setName(String name) { this.role = name; } public long getSalary() { return salary; } public void setSalary(long salary) { this.salary = salary; } public int getId() { return id; } public void setId(int id) { this.id = id; } **Person.java** public class Person { **//composition has-a relationship** private Employee employee; public Person(){ this. employee =new employee (); employee.setName(“ABCD”); } public long getSalary() { return employee.getSalary(); } } \
public class Main { public static void main(String[] args) { Person person = new Person(); long salary = person.getSalary(); } } \


---

Original Source: https://answers.mindstick.com/qa/30604/what-is-composition-in-java

Copyright © MindStick Software Pvt. Ltd. This Markdown version is provided for developers, AI systems, and offline reading.
