Sec-88
  • πŸ§‘Whoami
  • πŸ•ΈοΈWeb-AppSec
    • Features Abuse
      • 2FA
      • Ban Feature
      • CAPTCHA
      • Commenting
      • Contact us
      • File-Upload
      • Inviting Feature
      • Messaging Features
      • Money-Related Features
      • Newsletter
      • Profile - Settings
      • Registration
      • Reset Password
      • Review
      • Rich Editor/Text
      • Social Sharing
      • Billing-Shipping Address Management
      • Integrations - Webhooks
      • API Key Management
    • Reconnaissance
      • Attacking Organizations with big scopes
    • Subdomain Enumeration
    • Fingerprinting
    • Dorking
    • XSS-HTML Injection
    • Improper Authentication
      • JWT Security
    • OAUTH Misconfigurations
      • OAuth 2.0 Basics
      • OAUTH Misconfigurations
    • Auth0 Misconfigurations
    • Broken Access Control
      • Insecure Direct Object References (IDOR)
      • 403 Bypass
    • Broken Link Injection
    • Command Injection
    • CORS
    • CRLF
    • CSRF
    • Host Header Attacks
    • HTTP request smuggling
    • JSON Request Testing
    • LFI
      • LFI to RCE
    • No Rate Limit
    • Parameters Manual Testing
    • Open Redirect
    • Registration & Takeover Bugs
    • Remote Code Execution (RCE)
    • Session Fixation
    • SQL Injection
      • SQL To RCE
    • SSRF
    • SSTI
    • Subdomain Takeover
    • Web Caching Vulnerabilities
    • WebSockets
    • XXE
      • XXE to RCE
    • Cookie Based Attacks
    • CMS
      • AEM [Adobe CMS]
    • XSSI (Cross Site Script Inclusion)
    • NoSQL injection
    • Local VS Remote Session Fixation
    • Protection
      • Security Mechanisms for Websites
      • Cookie Flags
      • SameSite Cookie Restrictions
      • Same-origin policy (SOP)
      • CSP
    • Hacking IIS Applications
    • Dependency Confusion
    • Attacking Secondary Context
    • Hacking Web Sockets
    • IDN Homograph Attack
    • DNS Rebinding Attack
    • LLM Hacking Checklist
    • Bypass URL Filtration
    • Cross-Site Path Traversal (CSPT)
    • PostMessage Security
    • Prototype Pollution
      • Client-Side Prototype Pollution
      • Server-Side prototype pollution
    • Tools-Extensions-Bookmarks
    • WAF Bypassing Techniques
    • SSL/TLS Certificate Lifecycle
    • Serialization in .NET
    • Client-Side Attacks
      • JavaScript Analysis
    • Bug Bounty Platforms/Programs
  • βœ‰οΈAPI-Sec
    • GraphQL API Security Testing
      • The Basics
      • GraphQL Communication
      • Setting Up a Vulnerable GraphQL Server
      • GraphQL Hacking Tools
      • GraphQL Attack Surface
      • RECONNAISSANCE
      • GraphQL DOS
      • Information Disclosure
      • AUTHENTICATION AND AUTHORIZATION BYPASSES
      • Injection Vulnerabilities in GraphQL
      • REQUEST FORGERY AND HIJACKING
      • VULNERABILITIES, REPORTS AND EXPLOITS
      • GraphQL Hacking Checklist
    • API Recon
    • API Token Attacks
    • Broken Object Level Authorization (BOLA)
    • Broken Authentication
    • Evasive Maneuvers
    • Improper Assets Management
    • Mass Assignment Attacks
    • SSRF
    • Injection Vulnerabilities
    • Excessive Data Exposure
    • OWASP API TOP 10 MindMap
    • Scanning APIs with OWASP ZAP
  • πŸ“±Android-AppSec
    • Setup Android App Pentesting environment on Arch
    • Setup Android App Pentesting environment on Mac M4
    • Setup Android Pentesting Environment on Debian Linux
    • Android App Fundamentals
      • Android Architecture
      • Android Security Model
      • Android App Components
        • Intents
        • Pending Intents
    • Android App Components Security Cheatsheet
    • Android App Pentesting Checklist
    • How To Get APK file for application
    • ADB Commands
    • APK structure
    • Android Permissions
    • Exported Activity Hacking
    • BroadcastReceiver Hacking
    • Content Provider Hacking
    • Signing the APK
    • Reverse Engineering APK
    • Deep Links Hacking
    • Drozer Cheat Sheet
    • SMALI
      • SMALI Cheat Sheet
      • Smali Code Patching Guide
    • Intent Redirection Vulnerability
    • Janus Vulnerability (CVE-2017-13156)
    • Task Hijacking
    • Hacking Labs
      • Injured Android
      • Hacking the VulnWebView Lab
      • Hacking InsecureBankv2 App
    • Frida Cheat Sheet
  • πŸ“ΆNetwork-Sec
    • Networking Fundamentals
    • Open Ports Security Testing
    • Vulnerability Scanning
    • Client Side Attacks
    • Port Redirection and Tunneling
    • Password Attacks
    • Privilege Escalation [PrevEsc]
      • Linux Privilege Escalation
    • Buffer Overflow (BOF)
      • VulnServer
      • Sync Breez Enterprize
      • Crashed CTF
      • BOF for Linux
    • AV Evasion
    • Post Exploitation
      • File Transfer
      • Maintaining Access
      • Pivoting
      • Clean Up
    • Active Directory
      • Basic AD Pentesting
  • πŸ’»Desktop AppSec
    • Thin Client vs. Thick Client
  • ☁️Cloud Sec
    • Salesforce Hacking
      • Basics
      • Salesforce SAAS Apps Hacking
    • Firebase
    • S3 Buckets Misconfigurations
  • πŸ‘¨β€πŸ’»Programming
    • HTML
    • JavaScript (JS)
      • window.location object
    • Python
      • Python Tips
      • Set
        • SetMethods
    • JAVA
      • Java Essentials
      • Java Essentials Code Notes
      • Java OOP1
      • JAVA OOP Principles
        • Inheritance
        • Method Overriding
        • Abstract Class
        • Interface
        • polymorphism
        • Encapsulation
        • Composition
      • Java OOP Challenges
      • Exception Handling
    • Go
      • Go Syntax Tutorial in one file
      • Methods and Interfaces
      • Go Slices
      • Go Maps
      • Go Functions
      • Concurrency
      • Read Files
      • Write Files
      • Package
        • How to make personal Package
        • regexp Packages
        • Json
        • bufio
        • Time
      • Signals-Exit
      • Unit Testing
  • πŸ–₯️Operating Systems
    • Linux
      • Linux Commands
      • Tools
      • Linux File System
      • Bash Scripting guide
      • tmux
      • Git
      • Install Go tools from private repositories using GitHub PAT
    • VPS
    • Burp Suite
  • ✍️Write-Ups
    • Hunting Methodology
    • API BAC leads to PII Data Disclosure
    • Misconfigured OATUH leads to Pre-Account Takeover
    • Automating Bug Bounty with GitHub Actions
    • From Recon to Reward: My Bug Bounty Methodology when Hunting on Public Bug Bounty Programs
    • Exploring Subdomains: From Enumeration to Takeover Victory
    • 0-Click Account Takeover via Insecure Password Reset Feature
    • How a Simple Click Can Lead to Account Takeover: An OAuth Insecure Implementation Vulnerability
    • The Power Of IDOR even if it is unpredictable IDs
    • Unlocking the Weak Spot: Exploiting Insecure Password Reset Tokens
    • AI Under Siege: Discovering and Exploiting Vulnerabilities
    • Inside the Classroom: How We Hacked Our Way Past Authorization on a Leading EdTech Platform
    • How We Secured Our Client’s Platform Against Interaction-Free Account Thefts
    • Unchecked Privileges: The Hidden Risk of Role Escalation in Collaborative Platforms
    • Decoding Server Behavior: The Key to Mass Account Takeover
    • Exploiting JSON-Based CSRF: The Hidden Threat in Profile Management
    • How We Turned a Medium XSS into a High Bounty by Bypassing HttpOnly Cookie
Powered by GitBook
On this page

Was this helpful?

Edit on GitHub
  1. Programming
  2. JAVA
  3. JAVA OOP Principles

Composition

In Java, composition is a design principle that allows you to create complex objects by combining simpler objects or types. It is a way to achieve code reuse without using inheritance. Composition involves creating relationships between classes by having one class contain an instance of another class. This is in contrast to inheritance, where a class can inherit properties and behaviors from another class.

Here's a simple example to illustrate composition in Java:

// Simple class representing an Engine
class Engine {
    public void start() {
        System.out.println("Engine started");
    }
}

// Class representing a Car that uses composition to include an Engine
class Car {
    private Engine engine;

    public Car(Engine engine) {
        this.engine = engine;
    }

    public void start() {
        System.out.println("Car is starting");
        engine.start();
    }
}

public class CompositionExample {
    public static void main(String[] args) {
        // Create an Engine instance
        Engine carEngine = new Engine();

        // Create a Car instance, passing the Engine instance through the constructor
        Car myCar = new Car(carEngine);

        // Start the car, which internally starts the engine
        myCar.start();
    }
}

In this example:

  • The Engine class has a method start() that prints a message indicating the engine is starting.

  • The Car class has a composition relationship with the Engine class. It contains an instance of the Engine class as a private member variable.

  • The Car class also has a method start(), which, in addition to printing a message for the car starting, delegates the task of starting the engine to the Engine instance.

By using composition, you can create modular and flexible code. If you later need to change the behavior of the Engine class, it won't affect the Car class as long as the interface between them remains the same. This is in contrast to inheritance, where changes to a superclass can potentially affect all subclasses.

Example 2

// Java program to Illustrate Concept of Composition

// Importing required classes
import java.io.*;
import java.util.*;

// Class 1
// Helper class
// Book class
class Book {

	// Member variables of this class
	public String title;
	public String author;

	// Constructor of this class
	Book(String title, String author)
	{

		// This keyword refers top current instance
		this.title = title;
		this.author = author;
	}
}

// Class 2
// Helper class
// Library class contains list of books.
class Library {

	// Reference to refer to list of books.
	private final List<Book> books;

	// Constructor of this class
	Library(List<Book> books)
	{

		// This keyword refers to current instance itself
		this.books = books;
	}

	// Method of this class
	// Getting the list of books
	public List<Book> getListOfBooksInLibrary()
	{
		return books;
	}
}

// Class 3
// Main class
class GFG {

	// Main driver method
	public static void main(String[] args)
	{

		// Creating the objects of class 1 (Book class)
		// inside main() method
		Book b1
			= new Book("EffectiveJ Java", "Joshua Bloch");
		Book b2
			= new Book("Thinking in Java", "Bruce Eckel");
		Book b3 = new Book("Java: The Complete Reference",
						"Herbert Schildt");

		// Creating the list which contains the
		// no. of books.
		List<Book> book = new ArrayList<Book>();

		// Adding books to List object
		// using standard add() method
		book.add(b1);
		book.add(b2);
		book.add(b3);

		// Creating an object of class 2
		Library library = new Library(book);

		// Calling method of class 2 and storing list of
		// books in List Here List is declared of type
		// Books(user-defined)
		List<Book> books
			= library.getListOfBooksInLibrary();

		// Iterating over for each loop
		for (Book bk : books) {

			// Print and display the title and author of
			// books inside List object
			System.out.println("Title : " + bk.title
							+ " and "
							+ " Author : " + bk.author);
		}
	}
}
PreviousEncapsulationNextJava OOP Challenges

Last updated 1 year ago

Was this helpful?

Credits:

πŸ‘¨β€πŸ’»
https://www.geeksforgeeks.org/composition-in-java/