惯性聚合 高效追踪和阅读你感兴趣的博客、新闻、科技资讯
阅读原文 在惯性聚合中打开

推荐订阅源

T
The Blog of Author Tim Ferriss
IT之家
IT之家
Engineering at Meta
Engineering at Meta
WordPress大学
WordPress大学
博客园 - 三生石上(FineUI控件)
博客园 - 聂微东
C
Check Point Blog
T
Tailwind CSS Blog
博客园 - Franky
H
Help Net Security
钛媒体:引领未来商业与生活新知
钛媒体:引领未来商业与生活新知
Google DeepMind News
Google DeepMind News
博客园 - 叶小钗
J
Java Code Geeks
腾讯CDC
罗磊的独立博客
爱范儿
爱范儿
阮一峰的网络日志
阮一峰的网络日志
Martin Fowler
Martin Fowler
酷 壳 – CoolShell
酷 壳 – CoolShell
I
InfoQ
B
Blog
V
Visual Studio Blog
F
Fortinet All Blogs

DEV Community

Authentication Security Deep Dive: From Brute Force to Salted Hashing (With Java Examples) Why AI Systems Don’t Fail — They Drift Spilling beans for how i learn for exam😁"Reinforcement Learning Cheat Sheet" I Replaced Chrome with Safari for AI Browser Automation. Here's What Broke (and What Finally Worked) How Python Borrows Other People's Work The $40 Architecture: Processing 1 Billion API Requests with 99.99% Uptime Vibe Coding: A Workflow Guide (From Zero to SaaS) Most webhook security guides protect the wrong side. The scary part is delivery. Headless CMS for TanStack Start: Build a Blog with Cosmic EU Age Verification App "Hacked in 2 Minutes" — What Actually Happened Comfy Cloud’s delete function does not actually remove files Running AI Models on GPU Cloud Servers: A Beginner Guide Event-driven media intelligence with AWS Step Functions and Bedrock I scored 500 AI prompts across 8 quality dimensions — here's what broke How to Call Google Gemini API from Next.js (Free Tier, No Backend Needed) The Portal Protocol: Reclaiming Human Connection in the Age of AI How to Fix Your Team's Scattered Knowledge Problem With a Self-Hosted Forum Intro to tc Cloud Functors: A Graph-First Mental Model for the Modern Cloud Designing Multi-Tenant Backends With Both Ownership and Team Access I Built a Neumorphic CSS Library with 77+ Components — Here's What I Learned PostgreSQL Performance Optimization: Why Connection Pooling Is Critical at Scale Cómo construí un SaaS multi-rubro para gestionar expensas en Argentina con FastAPI + Vue 3 🚀 I Built an Ethical Hacking Scanner Tool – Open Source Project I Replaced /usage and /context in Claude Code With a Single Statusline A Pythonic Way to Handle Emails (IMAP/SMTP) with Auto-Discovery and AI-Ready Design I Collected 8.9 Million Polymarket Price Points — Here's What I Found About How Markets Really Move EcoTrack AI — Carbon Footprint Tracker & Dashboard Everyone's Using AI. No One Agrees How. 5 self-hosted ebook managers worth trying in 2026 Building Your First AI Agent with LangChain: From Chatbot to Autonomous Assistant
Beyond Inheritance in Java: A Practical Guide to Composition
Vinayagam · 2026-06-04 · via DEV Community
Cover image for Beyond Inheritance in Java: A Practical Guide to Composition

Vinayagam

Introduction

In Java, inheritance is commonly used to reuse code using the extends keyword. However, inheritance is not always the best solution. In many real-world applications, developers prefer a more flexible and maintainable approach called composition.

This article explains how to share data both with inheritance and without inheritance, using simple examples, a relatable story, and the role of access modifiers.


A Simple Story to Understand

Consider a School and Student relationship:

  • A School does not become a Student
  • A School has Students

This highlights the difference:

  • Inheritance represents an IS-A relationship
  • Composition represents a HAS-A relationship

Using Inheritance (IS-A Relationship)

Student.java

package shop;

public class Student {
    protected String name = "Vinay";

    public void showName() {
        System.out.println(name);
    }
}

Enter fullscreen mode Exit fullscreen mode

School.java

package shop;

public class School extends Student {

    public static void main(String[] args) {
        School sc = new School();
        sc.showName();  // inherited method
    }
}

Enter fullscreen mode Exit fullscreen mode

Explanation

  • School extends Student, meaning School is treated as a Student
  • This is not logically correct for this scenario
  • protected allows access within subclasses

Using Composition (Without Inheritance)

Student.java

package shop;

public class Student {
    private String name = "Vinay";

    public String getName() {
        return name;
    }
}

Enter fullscreen mode Exit fullscreen mode

School.java

package shop;

public class School {

    public void display(Student s) {
        System.out.println(s.getName());
    }
}

Enter fullscreen mode Exit fullscreen mode

Main.java

package shop;

public class Main {

    public static void main(String[] args) {
        Student s = new Student();
        School sc = new School();

        sc.display(s);  // HAS-A relationship
    }
}

Enter fullscreen mode Exit fullscreen mode


Role of Access Modifiers

Access modifiers control how data is accessed:

  • private → accessible only within the same class
  • protected → accessible in subclasses
  • public → accessible everywhere

In composition:

  • Data is kept private
  • Access is provided through public getter methods

This improves data security and encapsulation.


Inheritance vs Composition

Feature Inheritance Composition
Relationship IS-A HAS-A
Flexibility Low High
Coupling Tight Loose
Real-world modeling Sometimes incorrect More accurate

When to Use Each

Use inheritance when:

  • There is a clear IS-A relationship
  • Example: Dog is an Animal

Use composition when:

  • There is a HAS-A relationship
  • Example: School has Students

References