• Java Arrays
  • Java Strings
  • Java Collection
  • Java 8 Tutorial
  • Java Multithreading
  • Java Exception Handling
  • Java Programs
  • Java Project
  • Java Collections Interview
  • Java Interview Questions
  • Spring Boot
  • Encapsulation in Java
  • Rules of Downcasting Objects in Java
  • Types of Classes in Java
  • How to Execute Instance Initialization Block (IIB) without Creating Object in Java?
  • Difference Between Data Hiding and Abstraction in Java
  • Four Main Object Oriented Programming Concepts of Java
  • Abstraction by Parameterization and Specification in Java
  • Accessing Grandparent’s member in Java using super
  • How to Call Method in Java
  • Object Oriented Programming (OOPs) Concept in Java
  • Difference Between Aggregation and Composition in Java
  • Difference between Abstraction and Encapsulation in Java with Examples
  • When We Need to Prevent Method Overriding in Java ?
  • Static Synchronization in Java
  • Abstract Class in Java
  • Class Type Casting in Java
  • Understanding OOPs and Abstraction using Real World Scenario
  • What is the Need of Inheritance in Java?
  • Difference between Compile-time and Run-time Polymorphism in Java

Composition in Java

The composition is a design technique in java to implement a has-a relationship. Java Inheritance is used for code reuse purposes and the same we can do by using composition. The composition is achieved by using an instance variable that refers to other objects. If an object contains the other object and the contained object cannot exist without the existence of that object, then it is called composition. In more specific words composition is a way of describing reference between two or more classes using instance variable and an instance should be created before it is used. 

what is composition java

The benefits of using Composition is as follows: 

  • Composition allows the reuse of code.
  • Java doesn’t support multiple inheritances but by using composition we can achieve it.
  • Composition offers better test-ability of a class.
  • By using composition, we are flexible enough to replace the implementation of a composed class with a better and improved version.
  • By using composition, we can also change the member objects at run time, to dynamically change the behaviour of your program.

Do remember the certain key points of composition in java which are as follows:

  • It represents a has-a relationship .
  • In composition, both entities are dependent on each other.
  • When there is a composition between two entities, the composed object cannot exist without the other entity. For example, A library can have no. of books on the same or different subjects. So, If the Library gets destroyed then All books within that particular library will be destroyed. This is because books can not exist without a library.
  • The composition is achieved by using an instance variable that refers to other objects.
  • We have to favour Composition over Inheritance.

Now let us finally refer to the below image in order to get a faint hint about the aggregation and to better understand how the composition works, let us take an example of the real-time library system.

Real-life Example: Library system   Let’s understand the composition in Java with the example of books and library. In this example, we create a class Book that contains data members like author, and title and create another class Library that has a reference to refer to the list of books. A library can have no. of books on the same or different subjects. So, If the Library gets destroyed then All books within that particular library will be destroyed. i.e., books can not exist without a library. The relationship between the library and books is composition.

Implementation:

Please Login to comment...

  • Java-Object Oriented
  • Computer Subject
  • 10 Best Tools to Convert DOC to DOCX
  • How To Summarize PDF Documents Using Google Bard for Free
  • Best free Android apps for Meditation and Mindfulness
  • TikTok Is Paying Creators To Up Its Search Game
  • 30 OOPs Interview Questions and Answers (2024)

Improve your Coding Skills with Practice

 alt=

What kind of Experience do you want to share?

  • Course List
  • First Steps
  • Introduction to Java
  • Environment setup
  • Workspace & First app
  • Basic Syntax
  • Variables & Constants
  • Control Flow
  • if, else-if, else, switch
  • for, foreach, while, do-while loops
  • Intermediate
  • Object-oriented Programming
  • OOP: Classes & Objects
  • OOP: Methods
  • OOP: Inheritance
  • OOP: Composition
  • OOP: Polymorphism
  • OOP: Encapsulation
  • Lambda Expressions
  • Enums (Enumerations)
  • List Collections
  • ArrayList Collection
  • Map Collections
  • HashMap Collection
  • Errors & Exceptions
  • Error & Exception Handling
  • Concurrency & Multi-threading

Java OOP: Composition Tutorial

In this Java tutorial we learn how to design loosely coupled applications with composition and why you should favor it above inheritance.

We cover how to instantiate a class within another class and how to access class members through multiple objects.

Lastly, we take a look at the pro's and cons of inheritance and composition.

  • What is composition

Convert inheritance to composition in Java

How to access an object in a class in java, why favor composition over inheritance, inheritance vs composition: pro's and cons.

  • Summary: Points to remember

Composition is a type of relationship between classes where one class contains another, instead of inheriting from another.

Composition should be favored above inheritance because it’s more flexible and allows us to design loosely coupled applications.

As an example, let’s consider an application that converts a video from one format to another. Typically, we would create a converter class that contains the details of the file and the functionality to convert it.

Then, we could have another class that inherits from the converter and sends a notification to the user when it’s done, pulling details like the name, size etc. from the parent converter class.

But what if we wanted to add audio file conversion to our application. We would have to write another notification class, this time inheriting from the audio converter.

This creates two problems:

  • The first problem is that we have two child classes that essentially do the same thing.
  • The second problem is that the children heavily depend on their respective parents. If we needed to change something in the parent converter classes, we could break the functionality of the children.

The solution is composition. Where inheritance can be thought of as an is-a relationship, composition can be thought of as a has-a relationship.

Instead of creating a child class that inherits functionality from a parent class, we create stand-alone classes that contain other classes.

Simply put, we create an object instance of a class inside another class.

We can convert any inheritance relationship to composition. To create this association between classes, we instantiate a new class object inside the constructor of the class we want to use it.

It’s similar to how we construct properties, except this time we create a new instance object of another class.

The ‘Converter’ class now has access to the functionality to sendPushMessage() without inheriting from the ‘Pushable’ class.

Functionality classes like Pushable are often named with “able”, “can” or “has”. Like Flyable, CanDrive, HasFood etc.

To access an object in a class we go another level deeper with dot notation. Let’s see the syntax first, then break it down.

Before we can access anything in ‘Class_2’, we have to create an object of it. Once we have the ‘class_2_obj’, we can access the ‘class_1_obj’ with dot notation.

Because ‘class_1_obj’ is an object itself, we have to use another level of dot notation to access its method.

An example will illustrate it better.

In the example above, we access the ‘push’ object that was created in the ‘Converter’ class constructor, from the ‘con1’ object. From there, we simply access the ‘sendPushMessage()’ through dot notation.

You might be asking, if composition only gives us indirect access, why should we use it?

Well, inheritance can be abused very easily. It could lead to a large hierarchy of classes that depend on each other, which is fragile.

If we change a class at the top of the hierarchy, any class that depend on it could be affected and may need to be changed as well.

As an example, let’s consider a class called ‘Animal’ and two child classes that inherit from it.

The ‘Dog’ and the ‘Cat’ can both eat() and walk() . But if we wanted to add a ‘Fish’, the hierarchy would need to be changed.

We would need something like a ‘Mammal’ class that inherits from ‘Animal’. Then, ‘Dog’ and ‘Cat’ can inherit from ‘Mammal’.

‘Fish’ will have to inherit from ‘Animal’, but also be separate from ‘Mammal’ and depending on what we want to do, ‘Animal’ may have to change.

Now let’s consider that instead of is-a animal, the classes now has-a animal.

This time, we add a class for any animal that can swim, and any animal that can walk.

The ‘Cat’ and ‘Dog’ classes can implement both ‘Walkable’ and’ Swimmable’. The ‘Fish’ class can implement Swimmable, skipping the others.

If we wanted to add a bird, we could add a ‘Flyable’ class, and the bird could implement ‘Walkable’, ‘Swimmable’ and ‘Flyable’.

The application is now loosely coupled, as each class stands on its own and is not dependent on another class. Let’s look at a full example.

We don’t mean that inheritance is a bad thing, a developer will still need to use inheritance from time to time.

Composition is just an alternative that we should consider, before using inheritance.

Let’s look some pro’s and cons of both inheritance and composition.

  • Inheritance Pro’s: Reusable code, easy to understand

Inheritance Cons: Tightly coupled, fragile, can be abused

Composition Pro’s: Reusable code, flexibility, loosely coupled

Composition Cons: Harder to understand

  • Composition is instantiating and accessing a class inside another instead of inheriting from it.
  • Any inheritance relationship can be converted into composition.
  • A class that’s instatiated inside another should use the this keyword to refer to the calling object.
  • Access to the inner object is done via dot notation, multiple levels deep.
  • We should typically try to favor composition over inheritance.
  • Convert inheritance
  • Access an object in a class
  • Why favor composition
  • Pro's and Cons
  • United States
  • United Kingdom

Rafael del Nero

By Rafael del Nero , Java Developer, JavaWorld |

Tease your mind and test your learning, with these quick introductions to challenging concepts in Java programming.

Java inheritance vs. composition: How to choose

Compare inheritance and composition, the two fundamental ways to relate java classes, then practice debugging classcastexceptions in java inheritance..

abstract connections / network / object / root / inheritance / hierarchy

When to use inheritance in Java

When to use composition in java, inheritance vs composition: two examples, method overriding with java inheritance, using constructors with inheritance, type casting and the classcastexception, take the java inheritance challenge.

  • What just happened?
  • Learn more about Java

Inheritance and composition are two programming techniques developers use to establish relationships between classes and objects. Whereas inheritance derives one class from another, composition defines a class as the sum of its parts.

Classes and objects created through inheritance are tightly coupled because changing the parent or superclass in an inheritance relationship risks breaking your code. Classes and objects created through composition are loosely coupled , meaning that you can more easily change the component parts without breaking your code.

Because loosely coupled code offers more flexibility, many developers have learned that composition is a better technique than inheritance, but the truth is more complex. Choosing a programming tool is similar to choosing the correct kitchen tool: You wouldn't use a butter knife to cut vegetables, and in the same way you shouldn't choose composition for every programming scenario. 

In this Java Challenger you'll learn the difference between inheritance and composition and how to decide which is correct for your program . Next, I'll introduce you to several important but challenging aspects of Java inheritance: method overriding, the super keyword, and type casting. Finally, you'll test what you've learned by working through an inheritance example line by line to determine what the output should be.

In object-oriented programming, we can use inheritance when we know there is an "is a" relationship between a child and its parent class. Some examples would be:

  • A person is a human.
  • A cat is an animal.
  • A car is a   vehicle.

In each case, the child or subclass is a specialized version of the parent or superclass. Inheriting from the superclass is an example of code reuse. To better understand this relationship, take a moment to study the Car class, which inherits from Vehicle :

When you are considering using inheritance, ask yourself whether the subclass really is a more specialized version of the superclass. In this case, a car is a type of vehicle, so the inheritance relationship makes sense. 

In object-oriented programming, we can use composition in cases where one object "has" (or is part of) another object. Some examples would be:

  • A car has a battery (a battery is part of a car).
  • A person has a heart  (a heart is part of a person).
  • A house has a living room (a living room is part of a house).

To better understand this type of relationship, consider the composition of a House :

In this case, we know that a house has a living room and a bedroom, so we can use the Bedroom and  LivingRoom objects in the composition of a House . 

Consider the following code. Is this a good example of inheritance?

In this case, the answer is no. The child class inherits many methods that it will never use, resulting in tightly coupled code that is both confusing and difficult to maintain. If you look closely, it is also clear that this code does not pass the "is a" test.

Now let's try the same example using composition:

Using composition for this scenario allows the  CharacterCompositionExample class to use just two of HashSet 's methods, without inheriting all of them. This results in simpler, less coupled code that will be easier to understand and maintain.

Inheritance allows us to reuse the methods and other attributes of one class in a new class, which is very convenient.  But for inheritance to really work, we also need to be able to change some of the inherited behavior within our new subclass.  For instance, we might want to specialize the sound a Cat makes:

This is an example of Java inheritance with method overriding. First, we extend the Animal class to create a new Cat class. Next, we override the Animal class's emitSound() method to get the specific sound the Cat makes. Even though we've declared the class type as Animal , when we instantiate it as Cat we will get the cat's meow. 

Does Java have multiple inheritance?

Unlike some languages, such as C++, Java does not allow multiple inheritance with classes. You can use multiple inheritance with interfaces, however. The difference between a class and an interface, in this case, is that interfaces don't keep state.

If you attempt multiple inheritance like I have below, the code won't compile:

A solution using classes would be to inherit one-by-one:

Another solution is to replace the classes with interfaces:

Using ‘super' to access parent classes methods

When two classes are related through inheritance, the child class must be able to access every accessible field, method, or constructor of its parent class. In Java, we use the reserved word super to ensure the child class can still access its parent's overridden method:

In this example, Character is the parent class for Moe.  Using super , we are able to access Character 's  move() method in order to give Moe a beer.

When one class inherits from another, the superclass's constructor always will be loaded first, before loading its subclass. In most cases, the reserved word super will be added automatically to the constructor.  However, if the superclass has a parameter in its constructor, we will have to deliberately invoke the super constructor, as shown below:

If the parent class has a constructor with at least one parameter, then we must declare the constructor in the subclass and use super to explicitly invoke the parent constructor. The super reserved word won't be added automatically and the code won't compile without it.  For example:

Casting is a way of explicitly communicating to the compiler that you really do intend to convert a given type.  It's like saying, "Hey, JVM, I know what I'm doing so please cast this class with this type." If a class you've cast isn't compatible with the class type you declared, you will get a ClassCastException .

In inheritance, we can assign the child class to the parent class without casting but we can't assign a parent class to the child class without using casting.

Consider the following example:

When we try to cast an Animal instance to a Dog we get an exception. This is because the Animal doesn't know anything about its child. It could be a cat, a bird, a lizard, etc. There is no information about the specific animal. 

The problem in this case is that we've instantiated Animal like this:

Then tried to cast it like this:

Because we don't have a Dog instance, it's impossible to assign an Animal to the Dog .  If we try, we will get a ClassCastException . 

In order to avoid the exception, we should instantiate the Dog like this:

then assign it to Animal :

In this case, because  we've extended the Animal class, the Dog instance doesn't even need to be cast; the Animal parent class type simply accepts the assignment.

Casting with supertypes

It's possible to declare a Dog with the supertype Animal , but if we want to invoke a specific method from Dog , we will need to cast it. As an example, what if we wanted to invoke the bark() method?  The Animal supertype has no way to know exactly what animal instance we're invoking, so we have to cast Dog manually before we can invoke the bark() method:

You can also use casting without assigning the object to a class type. This approach is handy when you don't want to declare another variable:

You've learned some important concepts of inheritance, so now it's time to try out an inheritance challenge. To start, study the following code:

  • Programming Languages
  • Software Development

what is composition java

Java Composition Tutorial

Avatar

By squashlabs, Last Updated: October 26, 2023

Java Composition Tutorial

Introduction to Composition

Basics of composition, composition vs inheritance, principles of composition, real world example: composition in an ecommerce application, use case: using composition in database connections, use case: composition in user authentication, best practice: composition over inheritance, best practice: ensuring robustness through composition, code snippet: implementing composition in a class, code snippet: accessing methods through composition, code snippet: overriding methods in composition, code snippet: composition with interfaces, code snippet: composition in multithreaded environment, performance considerations: composition and memory usage, performance considerations: composition and cpu usage, performance considerations: composition and speed, advanced technique: composition and design patterns, advanced technique: composition in distributed systems, error handling with composition.

Table of Contents

Composition is a fundamental concept in object-oriented programming that allows objects to be composed of other objects. It enables the creation of complex structures by combining simpler objects, promoting code reuse and modularity. In Java, composition is achieved by creating classes that contain references to other classes as instance variables.

Related Article: How To Parse JSON In Java

In composition, a class is composed of one or more objects of other classes. These objects are typically instantiated within the class and can be accessed and used by its methods. The composed objects become an integral part of the containing class, and their behavior can be leveraged to implement the desired functionality.

Let’s consider an example where we have a Car class that is composed of an Engine and a set of Wheels . The Car class represents the whole object, while the Engine and Wheels classes represent its parts. Here’s an example implementation:

In this example, the Car class contains an instance variable engine of type Engine and an array of wheels of type Wheel[] . Through composition, the Car class can leverage the functionality provided by the Engine and Wheel classes to perform operations such as starting the engine or rotating the wheels.

Composition and inheritance are two key concepts in object-oriented programming. While both approaches facilitate code reuse and promote modularity, they differ in their mechanisms and usage.

Inheritance allows a class to inherit properties and behaviors from a parent class, forming an “is-a” relationship. On the other hand, composition enables a class to be composed of other objects, forming a “has-a” relationship.

Composition offers more flexibility and is generally preferred over inheritance in many scenarios. It avoids the potential drawbacks of deep inheritance hierarchies, such as tight coupling, fragile base class problem, and limited code reuse. With composition, classes can be easily extended and modified by changing the composed objects, promoting better encapsulation and maintainability.

Consider the following example:

In this example, the Car class inherits from the Vehicle class, implying that a car is a type of vehicle. However, this approach can become limiting if we want to introduce new types of vehicles or modify the behavior of specific vehicle types. With composition, we can achieve greater flexibility:

Now, the Car class can be composed of a Vehicle object, allowing for easy modification and extension of the car’s behavior without affecting other vehicle types.

When using composition in Java, it is important to follow certain principles to ensure effective and maintainable code:

1. Favor composition over inheritance: As mentioned earlier, composition provides more flexibility and promotes code reuse without the limitations of inheritance. It allows for easy modification and extension of functionality.

2. Use interfaces and abstractions: By programming to interfaces and using abstractions, you can decouple the code from specific implementations. This makes it easier to switch or modify composed objects without affecting the containing class.

3. Encapsulate composed objects: Encapsulating the composed objects within the containing class ensures that their internal state and behavior are not directly accessible from outside. This promotes encapsulation and information hiding, making the code more robust and maintainable.

4. Use dependency injection: Instead of instantiating composed objects within the containing class, consider using dependency injection to inject them from external sources. This allows for better testability, modularity, and separation of concerns.

Related Article: How To Convert Array To List In Java

In the context of an eCommerce application, composition can be applied to model the relationships between different entities, such as products, orders, and customers.

Let’s consider an example where we have a Order class that is composed of Product objects and associated with a Customer object. Here’s an example implementation:

In this example, the Order class is composed of a list of Product objects and associated with a Customer object. By using composition, the eCommerce application can manage orders with multiple products and associate them with the corresponding customer.

In the context of database connections, composition can be used to manage the lifecycle of connections and provide a clean interface to interact with the database.

Let’s consider an example where we have a DatabaseConnection class that is composed of a Connection object from a database driver library. Here’s an example implementation using the JDBC library for connecting to a MySQL database:

In this example, the DatabaseConnection class is composed of a Connection object. The constructor initializes the connection using the provided URL, username, and password. The close() method is used to close the connection when it is no longer needed.

By using composition, the DatabaseConnection class encapsulates the complexity of managing the database connection and provides a clean interface to interact with the database. This promotes better separation of concerns and makes the code more maintainable.

User authentication is another area where composition can be effectively used to manage the authentication process and provide a flexible solution.

Let’s consider an example where we have a UserAuthenticator class that is composed of one or more Authenticator objects. Each Authenticator represents a specific authentication method, such as username/password authentication, social login authentication, or multi-factor authentication.

In this example, the UserAuthenticator class is composed of a list of Authenticator objects. The authenticate() method iterates through the authenticators and attempts to authenticate the user using each method until a successful authentication is achieved.

By using composition, the UserAuthenticator class provides a flexible solution that can support multiple authentication methods. New authenticators can be easily added or modified without affecting the overall authentication process.

Related Article: How To Iterate Over Entries In A Java Map

The principle of “composition over inheritance” suggests that favoring composition is often a better design choice than relying solely on inheritance. This best practice promotes code reuse, modularity, and flexibility.

Inheritance can lead to tight coupling and make the codebase more rigid and difficult to maintain. By using composition, classes can be easily extended and modified by changing the composed objects. This promotes better encapsulation, separation of concerns, and code reuse.

In this example, the Car class inherits from the Vehicle class. However, if we want to introduce new types of vehicles or modify the behavior of specific vehicle types, it can become limiting. By using composition, we can achieve greater flexibility:

In addition to promoting code reuse and flexibility, composition can also contribute to the robustness of a software system. By encapsulating composed objects and using interfaces or abstractions, you can ensure that the code is resilient to changes and errors.

In this example, the Application class is composed of a Logger object. The run() method of the application logs any errors that occur during execution using the logger. By using composition and programming to an interface ( Logger ), the application is resilient to changes in the logging implementation. It can easily switch between different loggers (e.g., FileLogger , ConsoleLogger ) without modifying the application code.

By encapsulating composed objects and programming to abstractions, you can ensure that the code is more robust and adaptable to changes and errors. This promotes better error handling and maintainability.

To implement composition in a class, you need to define instance variables that represent the composed objects and use them within the class methods to perform desired operations.

Here’s an example of implementing composition in a class representing a House :

In this example, the House class is composed of three Room objects: kitchen , livingRoom , and bedroom . The enterHouse() method demonstrates how the composed objects can be used to perform specific operations. When calling enterHouse() , the house is entered, and actions are performed in each room.

By using composition, the House class can leverage the functionality provided by the Room objects to perform operations specific to each room, promoting modularity and code reuse.

Related Article: How To Split A String In Java

To access methods of composed objects through composition, you can use the instance variables representing the composed objects and invoke their methods within the containing class.

Here’s an example that demonstrates accessing methods of composed objects in a Car class:

In this example, the Car class is composed of an Engine object and an array of Wheel objects. The startEngine() method invokes the start() method of the Engine object, and the rotateWheels() method iterates through the wheels array and invokes the rotate() method of each Wheel object.

By using composition, the Car class can access and utilize the methods of the composed objects to perform operations specific to the car, promoting modularity and encapsulation.

In composition, methods of composed objects can be overridden in the containing class to customize behavior or add additional functionality.

Here’s an example that demonstrates overriding a method of a composed object in a Car class:

In this example, the Car class is composed of an Engine object. The startEngine() method invokes the start() method of the Engine object. The Engine class defines the default behavior of starting an engine, while the ElectricEngine class extends the Engine class and overrides the start() method to add additional functionality specific to an electric engine.

By using composition and method overriding, the Car class can customize the behavior of the composed Engine object to handle different engine types.

Composition with interfaces allows for greater flexibility and decoupling of code from specific implementations. By programming to interfaces, classes can be composed of objects that implement the same interface, making it easier to switch or modify composed objects without affecting the containing class.

Here’s an example that demonstrates composition with interfaces in a Car class:

In this example, the Engine interface defines the contract for an engine, and the PetrolEngine and DieselEngine classes implement the Engine interface. The Car class is composed of an Engine object, which can be either a PetrolEngine or a DieselEngine object.

By using composition with interfaces, the Car class can be easily configured to use different engine types by providing the appropriate implementation of the Engine interface. This promotes better modularity, code reuse, and flexibility.

Related Article: How To Convert Java Objects To JSON With Jackson

When using composition in a multithreaded environment, it is important to ensure thread safety and proper synchronization to avoid race conditions and other concurrency issues.

Here’s an example that demonstrates composition in a multithreaded environment using the ExecutorService class from the java.util.concurrent package:

In this example, the TaskExecutor class is composed of an ExecutorService object, which is responsible for executing tasks in a multithreaded environment. The executeTask() method submits a Task object to the executor service for execution, and the shutdown() method shuts down the executor service when it is no longer needed.

By using composition and the ExecutorService class, the TaskExecutor class can leverage the thread management capabilities provided by the executor service to handle concurrent execution of tasks.

When using composition, it is important to consider the impact on memory usage, especially when dealing with large-scale systems or resource-constrained environments.

Composition involves creating objects and holding references to them within other objects. This can result in increased memory usage, as each composed object requires memory allocation and storage.

To mitigate excessive memory usage, consider the following best practices:

1. Minimize unnecessary composition: Only compose objects when it is necessary for the desired functionality. Avoid excessive nesting of objects or creating overly complex object hierarchies.

2. Use lazy initialization: Delay the instantiation of composed objects until they are actually needed. This can help reduce memory usage by creating objects on-demand rather than upfront.

3. Implement object pooling: Reuse already created objects instead of creating new objects when possible. This can be particularly useful in scenarios where objects are frequently created and destroyed.

4. Employ efficient data structures: Choose appropriate data structures to store composed objects. For example, use arrays or lists where appropriate to efficiently store collections of objects.

In addition to memory usage, composition can also impact CPU usage, especially when dealing with computationally intensive operations or frequent method invocations.

When using composition, each method invocation on a composed object adds an additional layer of method dispatch and execution, which can result in increased CPU usage.

To optimize CPU usage in composition-heavy code, consider the following best practices:

1. Minimize unnecessary method invocations: Only invoke methods on composed objects when necessary. Avoid redundant or unnecessary method calls that do not contribute to the desired functionality.

2. Use method memoization: Cache the results of expensive method invocations on composed objects to avoid recomputation. This can be particularly useful in scenarios where the same method is invoked multiple times with the same arguments.

3. Optimize method implementations: Optimize the implementation of methods in composed objects to reduce their computational complexity. Employ efficient algorithms and data structures to improve the performance of critical operations.

4. Employ parallelization: If applicable, parallelize computationally intensive operations across multiple threads or processes to leverage the full processing power of the system.

Related Article: Storing Contact Information in Java Data Structures

Composition can have an impact on the speed of an application, particularly in terms of method dispatch and object traversal. While the performance impact can vary depending on the specific implementation and use case, it is important to be mindful of potential bottlenecks.

To optimize speed in composition-heavy code, consider the following best practices:

1. Minimize method dispatch overhead: Reduce the number of method invocations and method dispatches by carefully designing the composition structure and minimizing unnecessary method calls.

2. Optimize object traversal: When traversing composed objects, use efficient algorithms and data structures that minimize the number of object lookups or iterations. This can help improve the speed of operations that involve accessing or manipulating composed objects.

3. Employ caching and memoization: Cache frequently accessed or computed values to avoid redundant computations and improve overall speed. This can be particularly useful in scenarios where the same values are accessed or computed multiple times.

4. Profile and optimize critical sections: Identify and profile critical sections of the code that are performance-sensitive. Use profiling tools to identify potential bottlenecks and optimize the corresponding code to improve speed.

Composition can be effectively used in conjunction with various design patterns to solve complex software engineering problems. By leveraging composition, design patterns can provide elegant and flexible solutions to common design challenges.

Here are a few examples of design patterns that make use of composition:

1. Strategy Pattern: The strategy pattern allows you to define a family of algorithms, encapsulate each one as a separate class, and make them interchangeable. Composition can be used to inject the appropriate strategy object into the context class.

2. Observer Pattern: The observer pattern defines a one-to-many dependency between objects, where changes in one object trigger updates in dependent objects. Composition can be used to maintain a collection of observers and manage their registration and notification.

3. Decorator Pattern: The decorator pattern allows behavior to be added to an individual object dynamically. Composition is used to wrap the original object with a series of decorators, each adding a specific behavior.

4. Composite Pattern: The composite pattern allows you to compose objects into tree structures to represent part-whole hierarchies. Composition is used to represent the relationships between composite and leaf objects.

By combining composition with design patterns, you can create flexible, modular, and extensible software designs that are easier to understand, maintain, and evolve.

Composition can be applied to distributed systems to build scalable and modular architectures. By composing small, independent services, you can create complex systems that are easier to develop, deploy, and manage.

In a distributed system, each service encapsulates a specific functionality and communicates with other services through well-defined interfaces. This composition of services enables the system to scale horizontally, handle failures gracefully, and evolve independently.

Here are a few key considerations when using composition in distributed systems:

1. Service Interface Design: Define clear and well-documented interfaces for each service to promote loose coupling and interoperability. Use technologies such as REST or gRPC to facilitate communication between services.

2. Service Discovery and Orchestration: Utilize service discovery mechanisms to locate and connect services dynamically. Use orchestration tools like Kubernetes or Docker Swarm to manage the deployment and lifecycle of services.

3. Cross-Service Communication: Design communication patterns between services, such as synchronous request-response, asynchronous messaging, or event-driven architectures. Use message queues, publish-subscribe systems, or event-driven frameworks to enable seamless communication.

4. Fault Tolerance and Resilience: Implement fault tolerance mechanisms, such as retries, circuit breakers, and bulkheads, to handle failures and ensure the system remains operational even in the presence of partial failures.

By leveraging composition in distributed systems, you can create scalable and modular architectures that are resilient, flexible, and easier to maintain.

Related Article: How to Convert JSON String to Java Object

Error handling with composition involves managing errors that occur within composed objects and propagating them to the containing class or handling them locally.

Here are a few best practices for error handling with composition:

1. Propagating Errors: When an error occurs within a composed object, propagate the error to the containing class by throwing an exception or returning an error code. This allows the containing class to handle the error appropriately.

2. Error Handling Strategies: Define error handling strategies for the containing class to handle propagated errors. This can include logging the error, retrying the operation, or providing fallback behavior.

3. Error Recovery in Composed Objects: Implement error recovery mechanisms within composed objects to handle errors locally and provide appropriate fallback behavior. This can involve retrying the operation, using default values, or rolling back changes.

4. Consistent Error Reporting: Use consistent error reporting mechanisms across composed objects to provide clear and meaningful error messages. This helps with debugging and identifying the root cause of errors.

Squash: a faster way to build and deploy Web Apps for testing

  Cloud Dev Environments

  Test/QA enviroments

  Staging

One-click preview environments for each branch of code.

More Articles from the How to Write Java Code: From Basics to Advanced Concepts series:

How to generate random integers in a range in java.

Generating random integers within a specific range in Java is made easy with the Random class. This article explores the usage of java.util.Random and ThreadLocalRandom... read more

How to Reverse a String in Java

This article serves as a guide on reversing a string in Java programming language. It explores two main approaches: using a StringBuilder and using a char array.... read more

How to Retrieve Current Date and Time in Java

Obtain the current date and time in Java using various approaches. Learn how to use the java.util.Date class and the java.time.LocalDateTime class to retrieve the... read more

Java Equals Hashcode Tutorial

Learn how to implement equals and hashcode methods in Java. This tutorial covers the basics of hashcode, constructing the equals method, practical use cases, best... read more

How To Convert String To Int In Java

How to convert a string to an int in Java? This article provides clear instructions using two approaches: Integer.parseInt() and Integer.valueOf(). Learn the process and... read more

Java Hashmap Tutorial

This article provides a comprehensive guide on efficiently using Java Hashmap. It covers various use cases, best practices, real-world examples, performance... read more

What is Composition in Java With Examples

What is Composition in Java With Examples

Java is a versatile language that supports object-oriented programming and code reusability with building relationships between two classes. There are two types of relationships or associations in Java used to reuse a code and reduce duplicity from one class to another.

These relationships are IS-A(Inheritance) and HAS-A (Association). While there is a tight coupling between the IS-A classes, HAS-A classes are loosely coupled and more preferable for the programmers.

The HAS-A relationship is divided into two types, viz., aggregation and composition in Java . This article is based on the OOP concept of composition. We will see many real-life examples of how the composition is coded and the advantages gained when implemented.

Check out our free courses related to software development.

Ads of upGrad blog

Explore Our Software Development Free Courses

A brief narration of associations or relationships in java.

In object-oriented programming, objects are related to each other and use the common functionality between them. This is where the topics of Inheritance, Association, Aggregation, and Composition in Java programs come.

  Inheritance (IS-A) and Association (HAS-A) in Java

Check Out upGrad’s Java Bootcamp

1. Inheritance (IS-A)

An IS-A relationship signifies that one object is a type of another. It is implemented using ‘extends’ and ‘implements’ keywords.

Example: HP IS-A laptop

Our learners also read: Learn java online free !

2. Association (HAS-A)

A HAS-A relationship signifies that a class has a relationship with another class. For instance, Class A holds Class B’s reference and can access all properties of class B.

Example: Human body HAS-A Heart

what is composition java

3. Aggregation Vs Composition

Has-A relationship or Association can be divided into aggregation and composition. An aggregation container class and referenced class can have an independent existence. A composition reference class cannot exist if the container class is destroyed.

Check Out upGrad’s Advanced Certification in Blockchain   

Let’s take an example to understand aggregation and composition. A car has its parts e.g., engines, wheels, music player, etc. The car cannot function without an engine and wheels but can function without a music player. Here the engine and car have a composition relation, and the car and music player have an aggregation relationship. In the case of Aggregation, an object can exist without being part of the main object.

Composition Vs. Inheritance

what is composition java

Composition in Java

A composition in Java between two objects associated with each other exists when there is a strong relationship between one class and another. Other classes cannot exist without the owner or parent class. For example, A ‘Human’ class is a composition of Heart and lungs . When the human object dies, nobody parts exist.

The composition is a restricted form of Aggregation. In Composition, one class includes another class and is dependent on it so that it cannot functionally exist without another class.

In-Demand Software Development Skills

upGrad’s Exclusive Software and Tech Webinar for you –

SAAS Business – What is So Different?

Implementation of Composition in Java

The engine and car relationship are implemented using Java classes as below. In Java, the ‘final’ keyword is used to represent Composition. This is because the ‘Owner’ object expects a part object to be available and function by making it ‘final’ .

public class Car {

           private final Engine engine; 

     public Car (){

    engine  = new Engine();

  class Engine {

private String type;

Let us take another example that depicts both inheritance and composition.

what is composition java

Source  

In this program, the class Honda is a Car and extends from the class Car. The car engine Object is used in the Honda class.

Car Colour = Black; Maximum Speed = 160

The car engine has started. 

The output is derived using composition and shows the details of the Honda Jazz car.

Explore our Popular Software Engineering Courses

Uml denotations of association.

The relationships of association, aggregation, and composition in Java between classes A and B are represented as follows in UML diagrams:

Association: A—->B

Composition: A—–<filled>B

Aggregation: A—–<>B

Get Software Engineering degrees online from the World’s top Universities. Earn Executive PG Programs, Advanced Certificate Programs, or Masters Programs to fast-track your career.

Learn Java Tutorials

Benefits of composition in java.

Using composition design technique in Java offers the following benefits:

  • It is always feasible to “prefer object composition over class inheritance”. Classes achieve polymorphism and code reuse by composition.
  • The composition is flexible, where you can change class implementation at run-time by changing the included object, and change its behaviour.
  • A composition-based design has a lesser number of classes.
  • THE “HAS-A” relationship between classes is semantically correct than the “IS-A” relationship.
  • Composition in Java offers better class testability that is especially useful in test-driven development.
  • It is possible to achieve “multiple inheritances” in languages by composing multiple objects into one.
  • In composition, there is no conflict between methods or property names.

Check out all trending Java Tutorials in 2024. 

Features of Composition in Java

Composition is a fundamental concept in Java programming that enables the creation of complex objects by combining simpler ones along with description, what is composition in java with example.  It facilitates code reuse, maintainability, and flexibility in designing software applications. Let’s explore the key features of composition in Java:

Object Composition

Object composition involves creating complex objects by combining simpler ones. In Java, this is achieved by defining classes that contain references to other classes as instance variables. This allows objects to be composed of other objects, forming a hierarchical structure.

Has-a Relationship

Composition establishes a “has-a” relationship between classes, where one class contains objects of another class. This relationship signifies that a class has references to other classes to fulfill its functionality. For example, a Car class may have instances of Engine, Wheels, and Seats classes and understanding what is composition in java.

Code Reusability

Composition promotes code reusability by allowing the reuse of existing classes within new classes. Instead of inheriting behavior through inheritance, classes can reuse functionality by containing instances of other classes. This enhances modularity and reduces code duplication, composition example in java.

Encapsulation

Encapsulation is maintained through composition as the internal details of the composed objects are hidden from the outside world. Each class manages its own state and behavior, providing a clear separation of concerns. This enhances code maintainability and reduces the risk of unintended side effects and composition writing examples.

Flexibility and Modifiability

Composition offers greater flexibility compared to inheritance, as it allows classes to change behavior dynamically by replacing or modifying the objects they contain. This promotes a modular design approach, where individual components can be modified or extended without affecting the entire system.

Dynamic Behavior

With composition, the behavior of an object can be dynamically changed at runtime by replacing its constituent objects. This dynamic composition enables the creation of highly adaptable and customizable systems, where different configurations of objects can be used to achieve varying functionality, with an understanding of aggregation and composition in java.

Loose Coupling

Composition helps in achieving loose coupling between classes, as objects are accessed through interfaces rather than concrete implementations. This reduces dependencies between classes and promotes better code maintainability and testability.

Granular Control

With composition, developers have granular control over the behavior and state of objects. They can selectively expose certain functionalities of composed objects while encapsulating others, providing a clear interface for interaction with the object, like composition in java.

Encapsulation and Modularity

Composition promotes encapsulation, which is the practice of bundling data and methods that operate on that data within a single unit, with an understanding of object composition in java . By encapsulating related functionalities into separate classes, you can create modular and reusable components. This modularity enhances code organization and makes it easier to understand, maintain, and extend, with examples of composition.

One of the primary benefits of composition is code reusability. Instead of inheriting behaviors from a single parent class, you can compose objects by combining multiple classes to achieve the desired functionality. This approach allows you to reuse existing classes in different contexts, reducing code duplication and promoting a more efficient development process.

Flexibility and Loose Coupling

Composition promotes loose coupling between classes, which means that the components of a system are independent and can be modified or replaced without affecting other parts of the codebase. This flexibility is essential for building scalable and maintainable applications, as it enables developers to make changes to one part of the system without impacting the entire application.

Better Control over Behavior

With composition, you have finer control over the behavior of your objects compared to inheritance. Instead of inheriting all the characteristics of a parent class, you can selectively choose which functionalities to include in a class by composing it with the appropriate components. This granularity allows you to design classes that are tailored to specific requirements, leading to cleaner and more efficient code.

Avoiding the Diamond Problem

Inheritance can result in the “diamond problem,” where ambiguity rises when a class inherits from any two or more classes that have an ancestor. Composition helps avoid this issue by allowing you to combine functionalities from multiple classes without creating complex inheritance hierarchies. This simplifies the design and prevents potential conflicts that may arise from multiple inheritance.

Facilitates Testing and Debugging

Composition facilitates unit testing and debugging by enabling you to isolate and test individual components independently. Since each class encapsulates a specific set of functionalities, you can easily mock dependencies and simulate different scenarios during testing. Additionally, debugging becomes more manageable as the codebase is divided into smaller, more focused units.

When to Use Composition in Java?

In Java programming, composition is a powerful concept used to build complex objects by combining simpler ones. It involves creating objects by incorporating other objects within them. Knowing when to utilize composition is essential for writing clean, maintainable, and efficient code, with various composition writing sample.

Understanding Composition

Composition establishes a “has-a” relationship between classes, where one class contains another as a part of its state. This is different from inheritance, which establishes an “is-a” relationship. In composition, the contained object does not inherit behavior from the containing class but rather is used to provide functionality or data, with english composition examples.

Encapsulation and Code Reusability

One of the primary use cases for composition is encapsulating functionality. By breaking down complex systems into smaller, more manageable components, you can encapsulate related functionality within separate classes. This promotes code reusability and modular design, making your codebase easier to understand and maintain.

Composition allows for greater flexibility in software design. Since objects are composed of other objects, you can easily modify or replace components without affecting the entire system. This modular approach simplifies testing and debugging and enables you to adapt your code to changing requirements more efficiently when association aggregation and composition in java.

Preventing Tight Coupling

Using composition helps avoid tight coupling between classes, which can make code brittle and difficult to maintain. By relying on interfaces or abstract classes, you can decouple components, making them interchangeable and reducing dependency on specific implementations. This enhances the scalability and extensibility of your codebase.

Promoting Single Responsibility Principle

Composition encourages adhering to the Single Responsibility Principle (SRP), which states that a class should have only one reason to change. By breaking down functionality into smaller, focused classes, each responsible for a specific task, you can create more cohesive and understandable code. This improves code maintainability and reduces the risk of introducing bugs when making modifications.

Example: GUI Components

Consider a graphical user interface (GUI) framework where various components such as buttons, text fields, and panels are composed to create complex interfaces. Each component encapsulates its behavior and appearance, allowing developers to mix and match them to design diverse user interfaces efficiently.

Composition in Java offers many advantages while programming and is one of the favoured design methods. In this article, we have tried to make you understand this important concept with real-life examples and practical code. Composition offers flexibility and robust code. Its code reusability feature helps in avoiding code duplication and achieving cost-effectiveness. This makes it one of the widely used methods in various programs.  

Learn composition in Java with upGrad’s Master of Science in a Computer Science course which is aimed to make you learn and upgrade your skills in software development.

Eligibility

A B achelor’s Degree with 50% or equivalent marks. No initial coding experience is needed.

The program fee starts at Rs.13, 095/month for Indian Residents and USD 5999 for International residents.

Profile

Arjun Mathur

Something went wrong

Our Trending Software Engineering Courses

  • Master of Science in Computer Science from LJMU
  • Executive PG Program in Software Development Specialisation in Full Stack Development from IIIT-B
  • Advanced Certificate Programme in Cyber Security from IIITB
  • Full Stack Software Development Bootcamp
  • Software Engineering Bootcamp from upGrad

Popular Software Development Skills

  • React Courses
  • Javascript Courses
  • Core Java Courses
  • Data Structures Courses
  • ReactJS Courses
  • NodeJS Courses
  • Blockchain Courses
  • SQL Courses
  • Full Stack Development Courses
  • Big Data Courses
  • Devops Courses
  • NFT Courses
  • Cyber Security Courses
  • Cloud Computing Courses
  • Database Design Courses
  • Crypto Courses
  • Python Courses

Our Popular Software Engineering Courses

Full Stack Development

Frequently Asked Questions (FAQs)

Multiple Inheritance refers to the feature of Java where it can gain features from more than one parent class or object. In Java, one class cannot be extended to more than one. Nevertheless, a class can carry out more than one interface which has assisted Java in removing the impossibility of multiple interferences. The rationale behind this is to prevent ambiguity. For instance, assume a situation where Class D extends class C and Class B and both these classes have the same method display. In this case, the Java compiler can't contemplate which method display to decipher. Thus, to avoid this multiple inheritances aren't supported in Java.

Aggregation refers to a 'has a' connection between two related objects. For instance, a department maintains multiple employees. Association refers to a 'has a' connection between two related objects. For instance, an employee possessing a communication address. Aggregation is highly flexible in nature whereas the association is inflexible. Association requires linkages to be mandatory whereas aggregation doesn't require linkages to be mandatory between objects. When we consider UML, the lines are used to represent association whereas in aggregation the diamond shape next to the assembly class depicts the aggregation relationship.

Inheritance is defined as the mechanism through which you can acquire the properties and behaviour of a class into another class. Encapsulation is the winding of data into a single unit which is known as class. Inheritance implies that a child class inherits the attributes from the parent class whereas encapsulation implies that a particular class should not have access to the private data of another class. In encapsulation, we should focus on what should be exposed in a class and what should not be exposed. When discussing the class, the decision should be based on data and behaviour.

Related Programs View All

Certification

40 Hrs Live, Expert-Led Sessions

2 High-Quality Practice Exams

View Program

what is composition java

Executive PG Program

IIIT-B Alumni Status

what is composition java

Master's Degree

40000+ Enrolled Learners

what is composition java

Job Assistance

32-Hr Training by Dustin Brimberry

Question Bank with 300+ Practice Qs

45 Hrs Live Expert-Led Training

Microsoft-Approved Curriculum

159+ Hours of Live Sessions

what is composition java

126+ Hours of Live Sessions

Fully Online

13+ Hrs Instructor-Led Sessions

Live Doubt-Solving Sessions

what is composition java

2 Unique Specialisations

300+ Hiring Partners

20+ Hrs Instructor-Led Sessions

16 Hrs Live Expert-Led Training

CLF-C02 Exam Prep Support

what is composition java

24 Hrs Live Expert-Led Training

4 Real-World Capstone Projects

17+ Hrs Instructor-Led Training

3 Real-World Capstone Projects

289 Hours of Self-Paced Learning

10+ Capstone Projects

490+ Hours Self-Paced Learning

4 Real-World Projects

690+ Hours Self-Paced Learning

Cloud Labs-Enabled Learning

288 Hours Self-Paced Learning

9 Capstone Projects

40 Hrs Live Expert-Led Sessions

2 Mock Exams, 9 Assessments

what is composition java

Executive PG Certification

GenAI integrated curriculum

what is composition java

Job Prep Support

Instructor-Led Sessions

Hands-on UI/UX

16 Hrs Live Expert-Led Sessions

12 Hrs Hand-On Practice

30+ Hrs Live Expert-Led Sessions

24+ Hrs Hands-On with Open Stack

2 Days Live, Expert-Led Sessions

34+ Hrs Instructor-Led Sessions

10 Real-World Live Projects

24 Hrs Live Expert-Led Sessions

16 Hrs Hand-On Practice

8 Hrs Instructor-Led Training

Case-Study Based Discussions

40 Hrs Instructor-Led Sessions

Hands-On Practice, Exam Support

24-Hrs Live Expert-Led Sessions

Regular Doubt-Clearing Sessions

Extensive Exam Prep Support

6 Hrs Live Expert-Led Sessions

440+ Hours Self-Paced Learning

400 Hours of Cloud Labs

15-Hrs Live Expert-Led Sessions

32 Hrs Live Expert-Led Sessions

28 Hrs Hand-On Practice

Mentorship by Industry Experts

24 Hrs Live Trainer-Led Sessions

Mentorship by Certified Trainers

Full Access to Digital Resources

16 Hrs Live Instructor-Led Sessions

80+ Hrs Hands-On with Cloud Labs

160+ Hours Live Instructor-Led Sessions

Hackathons and Mock Interviews

31+ Hrs Instructor-Led Sessions

120+ Hrs of Cloud Labs Access

35+ Hrs Instructor-Led Sessions

6 Real-World Live Projects

24+ Hrs Instructor-Led Training

Self-Paced Course by Nikolai Schuler

Access Digital Resources Library

300+ Hrs Live Expert-Led Training

90 Hrs Doubt Clearing Sessions

56 Hours Instructor-Led Sessions

78 Hrs Live Expert-Led Sessions

22 Hrs Live, Expert-Led Sessions

CISA Job Practice Exams

Explore Free Courses

Study Abroad Free Course

Learn more about the education system, top universities, entrance tests, course information, and employment opportunities in Canada through this course.

Marketing

Advance your career in the field of marketing with Industry relevant free courses

Data Science & Machine Learning

Build your foundation in one of the hottest industry of the 21st century

Management

Master industry-relevant skills that are required to become a leader and drive organizational success

Technology

Build essential technical skills to move forward in your career in these evolving times

Career Planning

Get insights from industry leaders and career counselors and learn how to stay ahead in your career

Law

Kickstart your career in law by building a solid foundation with these relevant free courses.

Chat GPT + Gen AI

Stay ahead of the curve and upskill yourself on Generative AI and ChatGPT

Soft Skills

Build your confidence by learning essential soft skills to help you become an Industry ready professional.

Study Abroad Free Course

Learn more about the education system, top universities, entrance tests, course information, and employment opportunities in USA through this course.

Suggested Blogs

Scrum Master Salary in India: For Freshers &#038; Experienced [2023]

by Rohan Vats

05 Mar 2024

SDE Developer Salary in India: For Freshers &#038; Experienced [2024]

by Prateek Singh

29 Feb 2024

Marquee Tag &#038; Attributes in HTML: Features, Uses, Examples

by venkatesh Rajanala

What is Coding? Uses of Coding for Software Engineer in 2024

by Harish K

Functions of Operating System: Features, Uses, Types

by Geetika Mathur

What is Information Technology? Definition and Examples

by spandita hati

50 Networking Interview Questions &#038; Answers (Freshers &#038; Experienced)

28 Feb 2024

Java Guides

Java Guides

Search this blog.

Check out my 10+ Udemy bestseller courses and discount coupons: Udemy Courses - Ramesh Fadatare

  • Composition in Java with Example

OOPS Tutorial

1. overview.

what is composition java

2. Intent/Definition

what is composition java

  • It represents a part-of-relationship.
  • In composition, both entities are dependent on each other.
  • When there is a composition between two entities, the composed object cannot exist without the other entity. For example, if order HAS-A line-items, then an order is a whole, and line items are parts. If an order is deleted then all corresponding line items for that order should be deleted.
  • Favor Composition over Inheritance.

3. Implementation with Example

Github repository.

Learn complete Java Programming with Examples -  Java Tutorial | Learn and Master in Java Programming with Examples

Related OOP Posts

  • Abstraction in Java with Example
  • Encapsulation in Java with Example
  • Inheritance in Java with Example
  • Polymorphism in Java with Example
  • Aggregation in Java with Example
  • Association in Java with Example
  • Cohesion in Java with Example
  • Coupling in Java with Example
  • Delegation in Java with Example

Post a Comment

Leave Comment

My Top and Bestseller Udemy Courses

  • Spring 6 and Spring Boot 3 for Beginners (Includes Projects)
  • Building Real-Time REST APIs with Spring Boot
  • Building Microservices with Spring Boot and Spring Cloud
  • Full-Stack Java Development with Spring Boot 3 & React
  • Testing Spring Boot Application with JUnit and Mockito
  • Master Spring Data JPA with Hibernate
  • Spring Boot Thymeleaf Real-Time Web Application - Blog App

Check out all my Udemy courses and updates: Udemy Courses - Ramesh Fadatare

Copyright © 2018 - 2025 Java Guides All rights reversed | Privacy Policy | Contact | About Me | YouTube | GitHub

Javatpoint Logo

Java Tutorial

Control statements, java object class, java inheritance, java polymorphism, java abstraction, java encapsulation, java oops misc.

JavaTpoint

  • Send your Feedback to [email protected]

Help Others, Please Share

facebook

Learn Latest Tutorials

Splunk tutorial

Transact-SQL

Tumblr tutorial

Reinforcement Learning

R Programming tutorial

R Programming

RxJS tutorial

React Native

Python Design Patterns

Python Design Patterns

Python Pillow tutorial

Python Pillow

Python Turtle tutorial

Python Turtle

Keras tutorial

Preparation

Aptitude

Verbal Ability

Interview Questions

Interview Questions

Company Interview Questions

Company Questions

Trending Technologies

Artificial Intelligence

Artificial Intelligence

AWS Tutorial

Cloud Computing

Hadoop tutorial

Data Science

Angular 7 Tutorial

Machine Learning

DevOps Tutorial

B.Tech / MCA

DBMS tutorial

Data Structures

DAA tutorial

Operating System

Computer Network tutorial

Computer Network

Compiler Design tutorial

Compiler Design

Computer Organization and Architecture

Computer Organization

Discrete Mathematics Tutorial

Discrete Mathematics

Ethical Hacking

Ethical Hacking

Computer Graphics Tutorial

Computer Graphics

Software Engineering

Software Engineering

html tutorial

Web Technology

Cyber Security tutorial

Cyber Security

Automata Tutorial

C Programming

C++ tutorial

Control System

Data Mining Tutorial

Data Mining

Data Warehouse Tutorial

Data Warehouse

RSS Feed

  • Español – América Latina
  • Português – Brasil
  • Tiếng Việt
  • Android Developers

Composition tracing

Traces are often the best source of information when first looking into a performance issue. They allow you to form a hypothesis of what the issue is and where to start looking.

There are two levels of tracing supported on Android: system tracing and method tracing.

Because system tracing only tracks areas specifically marked for tracing, it has low overhead and doesn't affect the performance of your app greatly. System tracing is great for seeing how long particular sections of your code are taking to run.

Method tracing tracks every function call in your app. This is very expensive and so it greatly affects the performance of your app, but it gives you a total picture of what is happening, what functions are being called, and how often they are being called.

By default, system traces do not include individual composable functions. They are available in method traces.

We are currently testing new system tracing functionality to show composable functions inside system traces. It gives you the low intrusiveness from system tracing, with method tracing levels of detail in composition.

Set up for composition tracing

To try out the recomposition tracing in your project, you need to update to at least the following versions:

  • Android Studio Flamingo
  • Compose UI: 1.3.0
  • Compose Compiler: 1.3.0

The device or emulator you run your trace on must also be at minimum API level 30.

Additionally, you need to add a new dependency on Compose Runtime Tracing:

With this dependency, when you take a system trace that includes recomposition, you can see the composable functions automatically.

Take a system trace

To take a system trace and see the new recomposition tracing in action, follow these steps:

Open the profiler:

what is composition java

Click CPU timeline

what is composition java

Navigate your app to the UI you want to trace and then select System Trace and Record

what is composition java

Use your app to cause recomposition and stop recording. Once the trace has been processed and appears, you should now be able to see the composables in the recomposition trace. You can use the keyboard and mouse to zoom and pan around the trace; if you are unfamiliar with navigating a trace, see the Record traces documentation.

what is composition java

Double-clicking on a composable in the chart takes you to its source code.

You can also see composables in the Flame Chart along with the file and line number:

what is composition java

APK size overhead

While we aimed to minimize the overhead of the feature as much as possible, there is an APK size increase for Compose apps coming from tracing strings embedded in the APK by the Compose compiler. This size increase can be relatively small if your app isn't using much Compose or larger for full Compose apps. These tracing strings are additionally unobfuscated so they can appear in tracing tools, as shown earlier. The Compose compiler injects them into all apps, starting with version 1.3.0.

The tracing strings can be removed in your production build by adding the following proguard rule:

These functions may change in the future, but any changes will be mentioned in the Compose release notes .

Note that keeping them in, while incurring some APK size cost, guarantees that the APK being profiled is the same one that the app users run.

Accurate timing

For accurate profiling, like with any performance testing, you need to make the app profileable and non-debuggable as per Profileable applications .

Capture a trace from terminal

It is possible to capture a composition trace from terminal. To do so, you have to perform the steps that Android Studio normally does for you automatically.

Add dependencies

First, add the additional dependencies to your app.

Generate a record command

  • Generate a record command using in Perfetto .

Manually add the track_event data source section as per following example:

Capture a trace

  • Launch the app and prepare the section you want to trace.

Enable tracing in the app by issuing a broadcast.

Start your recording command you created previously.

Open the trace

adb pull <location> the trace from the device (location specified in the record command).

Open in Perfetto .

Capture a trace with Jetpack Macrobenchmark

You can measure performance with Jetpack Macrobenchmark , which provides traces as results. To enable composition tracing with macrobenchmarks, you need to:

Add these additional dependencies to the Macrobenchmark test module:

Add androidx.benchmark.fullTracing.enable=true instrumentation argument before running benchmarks. Check Macrobenchmark instrumentation arguments for more information about Macrobenchmark instrumentation arguments.

We would love to hear your feedback on this feature, any bugs you find with it, and any requests you have. You can send us feedback via the issue tracker .

Content and code samples on this page are subject to the licenses described in the Content License . Java and OpenJDK are trademarks or registered trademarks of Oracle and/or its affiliates.

Last updated 2024-04-01 UTC.

share this!

April 3, 2024

This article has been reviewed according to Science X's editorial process and policies . Editors have highlighted the following attributes while ensuring the content's credibility:

fact-checked

peer-reviewed publication

trusted source

Researchers propose new step in tectonic squeeze that turns seafloor into mountains

by University of Texas at Austin

Researchers propose new step in tectonic squeeze that turns seafloor into mountains

Scientists use tiny minerals called zircons as geologic timekeepers. Often no bigger than a grain of sand, these crystals record chemical signatures of the geological environment where they formed. In a new study led by scientists at The University of Texas at Austin, researchers used them to describe what could be an overlooked step in a fundamental tectonic process that raises seafloors into mountains.

In a study published in the journal Geology , the researchers describe zircons from the Andes mountains of Patagonia. Although the zircons formed when tectonic plates were colliding, they have a chemical signature associated with when the plates were moving apart.

The researchers think that the unexpected signature could be explained by the mechanics of underlying tectonic plates that haven't yet been described in other models. This missing step involves a sort of geologic juicing in a magma chamber where zircons form before they reach the surface, with oceanic crust entering the chamber ahead of continental crust.

"If you put some oceanic basin below this magma, you have a change in the composition of this magma as it's incorporated," said the study's lead author Fernando Rey, a doctoral student at the UT Jackson School of Geosciences. "This is something that was not documented before this study."

Researchers propose new step in tectonic squeeze that turns seafloor into mountains

This theory of oceanic magma mixing is important because it could represent a transitional step in the formation of back arc basins—an important geological structure that shapes landscapes, geologic records and helps regulate the planet's climate.

These basins form between oceanic and continental tectonic plates , opening up as the plates move apart and closing as they come back together. While the opening of the basin creates oceanic crust, its closing squeezes the crust into mountains—bringing a geologic record of Earth history to the surface where humans can more easily access it, said co-author Matt Malkowski, an assistant professor at the Jackson School's Department of Earth and Planetary Sciences. What's more, the weathering of the ocean crust is a major driver of natural carbon dioxide storage.

"This is the Earth's way of sequestering carbon. Very effective on its own, but it may take hundreds of thousands if not millions of years," said Malkowski.

Malkowski collected the zircons examined in the study from rock and sediment samples at a field site in Patagonia. The samples captured the entire record of the back arc basin, called the Rocas Verdes Basin, from opening to closing.

When Rey started analyzing the chemical signatures of the zircons, nothing looked out of place at first. The zircons associated with an opening basin had the expected signature. However, when he started examining zircons associated with the closing of the basin, the signature didn't undergo the expected chemical shift—known to scientists as a "pull down" because of the way data plotting the isotope ratios goes from steadily rising to falling down.

When that pull down signature didn't show up until 200 million years later, appearing in zircons that formed 30 million years ago when the basin was already well into its closure phase, Rey and his collaborators hypothesized a scenario that could help explain the data.

Researchers propose new step in tectonic squeeze that turns seafloor into mountains

In their paper, they propose a model where the same tectonic forces that squeeze the oceanic crust into mountains could be underthrusting parts of that crust and pushing it toward the magmatic chamber where the zircons are formed—influencing the chemical signatures recorded in the crystals during the early to middle stages of closure. As the continents continue to squeeze together, the oceanic crust is eventually replaced by continental crust, the source of the pulldown signal.

The researchers think this transitional phase where zircons are juiced by oceanic crust could be part of back arc basins around the world. But there's a good reason why it hasn't been observed before, said Rey. Most back arc basins close faster than Patagonia did—in a few million years rather than tens of millions of years—meaning a shorter window of time in which these zircons can form.

Now that scientists have discovered this zircon signal in Patagonia, they can start looking for signs of it in zircons from other places. Rey is currently analyzing zircons from the Sea of Japan—a modern back arc basin that's in the early stages of closure—to see if there's signs of oceanic crust influencing the zircon signature.

This research adds to a record of discovery about back arc basins at UT Austin, said Malkowski. Professor Ian Dalziel authored a well-known Nature paper in 1974 that first recognized the Andes of Patagonia as forming due to back arc basin closure.

"Here we are 50 years later, and we're still learning new things about these rocks," Malkowski said.

Journal information: Nature , Geology

Provided by University of Texas at Austin

Explore further

Feedback to editors

what is composition java

Adult fish struggle to bounce back in marine protected areas, study finds

2 hours ago

what is composition java

Three companies in the running for NASA's next moon rover

what is composition java

Automated bioacoustics: Researchers are listening in on insects to better gauge environmental health

7 hours ago

what is composition java

New sunflower family tree reveals multiple origins of flower symmetry

14 hours ago

what is composition java

Researchers determine structure of new metal tellurate material with potential uses in solar energy and more

what is composition java

Evolution in action? New study finds possibility of nitrogen-fixing organelles

15 hours ago

what is composition java

How brown rats crawled off ships and conquered North American cities

what is composition java

Examining groundwater's role in ecosystem sustainability

what is composition java

Matador bugs use their own red flags to ward off predators

what is composition java

For mining in arid regions to be responsible, we must change how we think about water, say researchers

16 hours ago

Relevant PhysicsForums posts

Major earthquakes - 7.4 (7.2) mag and 6.4 mag near hualien, taiwan.

12 hours ago

Iceland warming up again - quakes swarming

Mar 30, 2024

Unlocking the Secrets of Prof. Verschure's Rosetta Stones

Mar 29, 2024

‘Our clouds take their orders from the stars,’ Henrik Svensmark on cosmic rays controlling cloud cover and thus climate

Mar 27, 2024

Higher Chance to get Lightning Strike by Large Power Consumption?

Mar 20, 2024

A very puzzling rock or a pallasite / mesmosiderite or a nothing burger

Mar 16, 2024

More from Earth Sciences

Related Stories

what is composition java

Zircons reveal the history of fluctuations in the oxidation state of crustal magmatism and the supercontinent cycle

Mar 13, 2024

what is composition java

Was plate tectonics occurring when life first formed on Earth?

Apr 4, 2023

what is composition java

Seeing through sediment reveals Red Sea tectonics

Mar 21, 2023

what is composition java

Earth's rock-solid connections between Canada and Australia contain clues about the origin of life (Update)

Jun 18, 2020

what is composition java

Ancient magma reveals signs of life in zircons from ancient Earth

Apr 6, 2023

what is composition java

International study reveals new insight into how continents were formed

Jun 11, 2021

Recommended for you

what is composition java

How NASA spotted El Niño changing the saltiness of coastal waters

17 hours ago

what is composition java

Researchers closer to near real-time disaster monitoring

19 hours ago

what is composition java

Research reveals pre-collapse monitoring of Kakhovka Dam, Ukraine

20 hours ago

what is composition java

Why artificial submarine curtains won't save West Antarctica's retreating glaciers

Let us know if there is a problem with our content.

Use this form if you have come across a typo, inaccuracy or would like to send an edit request for the content on this page. For general inquiries, please use our contact form . For general feedback, use the public comments section below (please adhere to guidelines ).

Please select the most appropriate category to facilitate processing of your request

Thank you for taking time to provide your feedback to the editors.

Your feedback is important to us. However, we do not guarantee individual replies due to the high volume of messages.

E-mail the story

Your email address is used only to let the recipient know who sent the email. Neither your address nor the recipient's address will be used for any other purpose. The information you enter will appear in your e-mail message and is not retained by Phys.org in any form.

Newsletter sign up

Get weekly and/or daily updates delivered to your inbox. You can unsubscribe at any time and we'll never share your details to third parties.

More information Privacy policy

Donate and enjoy an ad-free experience

We keep our content available to everyone. Consider supporting Science X's mission by getting a premium account.

E-mail newsletter

IMAGES

  1. Java Composition Tutorial

    what is composition java

  2. Composition in Java

    what is composition java

  3. What is Composition in Java With Examples

    what is composition java

  4. Association In Java

    what is composition java

  5. Java Association

    what is composition java

  6. class

    what is composition java

VIDEO

  1. ArrayList in Java

  2. Core Java

  3. Java Composition Detailed Class Example

  4. 24-JAVA-COMPOSITION ÖRNEK KODLAMA

  5. Core Java

  6. Aggregation Composition #composition #aggregation #programmingbasics

COMMENTS

  1. Composition in Java

    Composition in Java. The composition is a design technique in java to implement a has-a relationship. Java Inheritance is used for code reuse purposes and the same we can do by using composition. The composition is achieved by using an instance variable that refers to other objects. If an object contains the other object and the contained ...

  2. Composition, Aggregation, and Association in Java

    In this tutorial, we'll focus on Java's take on three sometimes easily mixed up types of relationships: composition, aggregation, and association. 2. Composition. Composition is a "belongs-to" type of relationship. It means that one of the objects is a logically larger structure, which contains the other object.

  3. Composition in Java

    Composition in Java. The Composition is a way to design or implement the "has-a" relationship. Composition and Inheritance both are design techniques. The Inheritance is used to implement the "is-a" relationship. The "has-a" relationship is used to ensure the code reusability in our program. In Composition, we use an instance variable that refers to another object.

  4. Inheritance and Composition (Is-a vs Has-a relationship) in Java

    1. Overview. Inheritance and composition — along with abstraction, encapsulation, and polymorphism — are cornerstones of object-oriented programming (OOP). In this tutorial, we'll cover the basics of inheritance and composition, and we'll focus strongly on spotting the differences between the two types of relationships. 2.

  5. Composition in Java Example

    Composition in java is the design technique to implement has-a relationship in classes. We can use java inheritance or Object composition in java for code reuse. Composition in Java. Java composition is achieved by using instance variables that refers to other objects. For example, a Person has a Job. Let's see this with a java composition ...

  6. OOP Concepts for Beginners: What is Composition?

    Composition is one of the key concepts of object-oriented programming languages like Java. It enables you to reuse code by modeling a has-a association between objects. If you combine the concept of composition with the encapsulation concept, you can exclude the reused classes from your API. That enables you to implement software components ...

  7. Java Composition

    This Java Composition tutorial explains what is Composition and Aggregation in Java and the differences between them: In the last couple of tutorials, we discussed inheritance in Java in detail. Inheritance in Java is a type of "IS-A" relationship which indicates that one object 'is a kind of' another object.

  8. Java OOP: Composition Tutorial

    In this Java tutorial we learn how to design loosely coupled applications with composition and why you should favor it above inheritance. We cover how to instantiate a class within another class and how to access class members through multiple objects. Lastly, we take a look at the pro's and cons of inheritance and composition.

  9. "Java Composition Tutorial: How to Use Composition to Create ...

    Composition allows us to create comp... In this video, we'll explore the concept of composition in Java, a fundamental technique in object-oriented programming.

  10. java

    They are absolutely different. Inheritance is an "is-a" relationship. Composition is a "has-a".. You do composition by having an instance of another class C as a field of your class, instead of extending C.A good example where composition would've been a lot better than inheritance is java.util.Stack, which currently extends java.util.Vector.This is now considered a blunder.

  11. Java inheritance vs. composition: How to choose

    Learn more about Java. Inheritance and composition are two programming techniques developers use to establish relationships between classes and objects. Whereas inheritance derives one class from ...

  12. Java Composition Tutorial

    Composition is a fundamental concept in object-oriented programming that allows objects to be composed of other objects. It enables the creation of complex structures by combining simpler objects, promoting code reuse and modularity. In Java, composition is achieved by creating classes that contain references to other classes as instance variables.

  13. What is Composition in Java With Examples

    Composition in Java. A composition in Java between two objects associated with each other exists when there is a strong relationship between one class and another. Other classes cannot exist without the owner or parent class. For example, A 'Human' class is a composition of Heart and lungs.

  14. Composition vs Inheritance

    Composition is the design technique in object-oriented programming to implement has-a relationship between objects. Composition in java is achieved by using instance variables of other objects. For example, a person who has a Job is implemented like below in java object-oriented programming.

  15. Composition in Java with Example

    Composition is an association that represents a part of a whole relationship where a part cannot exist without a whole. Example: University consists of several departments whenever university object destroys automatically all the department objects will be destroyed is without existing university object there is no chance of existing dependent ...

  16. java

    Composition. Composition is a special case of aggregation. In a more specific manner, a restricted aggregation is called composition. When an object contains the other object, if the contained object cannot exist without the existence of container object, then it is called composition. Concrete examples in Java from here and here. Dependency

  17. Composite Design Pattern in Java

    1. Introduction. In this quick tutorial, we'll introduce the composite design pattern in Java. We're going to describe the structure and the purpose of its use. 2. The Structure. The composite pattern is meant to allow treating individual objects and compositions of objects, or "composites" in the same way. It can be viewed as a tree ...

  18. Difference Between Aggregation and Composition in Java

    Composition is a strong type of "has-a" relationship because the containing object is its owner. So, objects are tightly coupled, which means if we delete the parent object, the child object will also get deleted with it. Let's take an example to understand how we can implement the logic for the Composition relationship in Java ...

  19. Inheritance (IS-A) vs. Composition (HAS-A) Relationship

    Composition is dynamic binding (run-time binding) while Inheritance is static binding (compile time binding) It is easier to add new subclasses (inheritance) than it is to add new front-end classes (composition) because inheritance comes with polymorphism. If you have a bit of code that relies only on a superclass interface, that code can work ...

  20. Composition tracing

    To take a system trace and see the new recomposition tracing in action, follow these steps: Open the profiler: Figure 2. Android Studio - Start Profiling. Click CPU timeline. Figure 3. Android Studio Profiler - CPU timeline. Navigate your app to the UI you want to trace and then select System Trace and Record. Figure 4.

  21. Researchers propose new step in tectonic squeeze that turns seafloor

    Scientists use tiny minerals called zircons as geologic timekeepers. Often no bigger than a grain of sand, these crystals record chemical signatures of the geological environment where they formed.