<?xml version="1.0" encoding="UTF-8"?><rss xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:content="http://purl.org/rss/1.0/modules/content/" xmlns:atom="http://www.w3.org/2005/Atom" version="2.0" xmlns:cc="http://cyber.law.harvard.edu/rss/creativeCommonsRssModule.html">
    <channel>
        <title><![CDATA[Stories by Rohit Chauhan on Medium]]></title>
        <description><![CDATA[Stories by Rohit Chauhan on Medium]]></description>
        <link>https://medium.com/@chauhan9911910013?source=rss-3e51deb5ec2a------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/0*aVDd_L2ZJTGRfNu0.</url>
            <title>Stories by Rohit Chauhan on Medium</title>
            <link>https://medium.com/@chauhan9911910013?source=rss-3e51deb5ec2a------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Wed, 02 Dec 2026 07:57:35 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@chauhan9911910013/feed" rel="self" type="application/rss+xml"/>
        <webMaster><![CDATA[yourfriends@medium.com]]></webMaster>
        <atom:link href="http://medium.superfeedr.com/" rel="hub"/>
        <item>
            <title><![CDATA[Abstract Classes vs. Interfaces in Java: The Ultimate Guide to Choosing Wisely]]></title>
            <link>https://medium.com/@chauhan9911910013/abstract-classes-vs-interfaces-in-java-the-ultimate-guide-to-choosing-wisely-5e9155a60d1e?source=rss-3e51deb5ec2a------2</link>
            <guid isPermaLink="false">https://medium.com/p/5e9155a60d1e</guid>
            <category><![CDATA[oops-concepts]]></category>
            <category><![CDATA[interfaces]]></category>
            <category><![CDATA[java-abstract-classes]]></category>
            <category><![CDATA[code-use]]></category>
            <category><![CDATA[template-method-pattern]]></category>
            <dc:creator><![CDATA[Rohit Chauhan]]></dc:creator>
            <pubDate>Fri, 24 Jan 2025 14:59:34 GMT</pubDate>
            <atom:updated>2025-01-24T15:14:51.515Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*UewM4u93AZDs8sXFWo4Dmw.png" /></figure><p><em>Why Default Methods Didn’t Kill Abstract Classes (And When to Use Each)</em></p><p>With the introduction of <strong>default methods</strong> in Java 8, many developers began to wonder: <em>“Do we even need abstract classes anymore?”</em> While interfaces have become more powerful, abstract classes remain a critical tool in Java design. Let’s break down their roles, limitations, and the <strong>key scenarios where abstract classes shine</strong>.</p><h3>Why Abstract Classes Still Matter in a World of Default Methods</h3><p>Java interfaces with default methods revolutionized API design by allowing reusable code within interfaces. However, abstract classes are <strong>far from obsolete</strong>. Here’s what interfaces still can’t do:</p><h3>1. State Management: Interfaces Can’t Hold Data</h3><p>Interfaces cannot define <strong>instance variables</strong> (state). Abstract classes, however, excel at managing shared state across subclasses.</p><pre>abstract class PaymentGateway {<br>    protected double balance; // State shared by all subclasses<br>    public void deposit(double amount) {<br>        balance += amount; // Reusable logic<br>    }<br>  abstract void processPayment(double amount);<br>}<br><br>class PayPalGateway extends PaymentGateway {<br>    @Override<br>    void processPayment(double amount) {<br>        balance -= amount; // Uses inherited state<br>    }<br>}</pre><h3>2. Constructors: Enforcing Initialization Logic</h3><p>Interfaces lack constructors, making them unsuitable for enforcing mandatory initialization steps. Abstract classes solve this:</p><pre>abstract class DatabaseConnector {<br>    private String url;<br>    // Subclasses MUST call this constructor<br>    public DatabaseConnector(String url) {<br>        if (url == null) throw new IllegalArgumentException(&quot;URL required!&quot;);<br>        this.url = url;<br>    }<br>    abstract void connect();<br>}<br>class MySQLConnector extends DatabaseConnector {<br>    public MySQLConnector(String url) {<br>        super(url); // Enforces URL initialization<br>    }<br>    @Override<br>    void connect() { /* ... */ }<br>}</pre><h3>3. Non-Public Methods: Hidden Helpers</h3><p>Interfaces force all methods to be public, while abstract classes support protected or package-private helpers:</p><pre>abstract class Logger {<br>    // Subclass-only helper method<br>    protected void logToFile(String message) {<br>        // Internal file-writing logic<br>    }<br>    abstract void log(String message);<br>}<br>class ConsoleLogger extends Logger {<br>    @Override<br>    void log(String message) {<br>        logToFile(message); // Reuse protected method<br>        System.out.println(message);<br>    }<br>}</pre><h3>When to Favor Abstract Classes Over Interfaces</h3><h3>Scenario 1: The Template Method Pattern</h3><p>Define a workflow skeleton with customizable steps:</p><pre>abstract class DataProcessor {<br>    // Final to lock the workflow<br>    public final void process() {<br>        validate();<br>        transform();<br>        save();<br>    }<br>    abstract void transform(); // Subclass implements<br>    private void validate() { /* Common validation */ }<br>    private void save() { /* Common save logic */ }<br>}<br>class CSVProcessor extends DataProcessor {<br>    @Override<br>    void transform() { /* CSV-specific logic */ }<br>}</pre><h3>Scenario 2: Partial Implementation with Shared State</h3><p>Share fields and methods across related subclasses:</p><pre>abstract class Vehicle {<br>    protected int fuelLevel; // Shared state<br>    public void refuel(int amount) {<br>        fuelLevel += amount;<br>    }<br>    abstract void move();<br>}<br>class Car extends Vehicle {<br>    @Override<br>    void move() {<br>        fuelLevel -= 10; // Uses inherited state<br>    }<br>}</pre><h3>Scenario 3: Enforcing Invariants</h3><p>Guarantee rules during object creation:</p><pre>abstract class Shape {<br>    private final String color;<br>    public Shape(String color) {<br>        if (color == null) throw new IllegalArgumentException(&quot;Color required&quot;);<br>        this.color = color; // Enforce invariant<br>    }<br>    abstract double area();<br>}<br>class Circle extends Shape {<br>    public Circle(String color) {<br>        super(color); // Ensures color is set<br>    }<br>    @Override<br>    double area() { /* ... */ }<br>}</pre><h3>Why You Can’t Use Interfaces for Everything</h3><h3>Problem 1: The Diamond Problem</h3><p>When two interfaces define the same default method, the implementing class <strong>must resolve conflicts manually</strong>:</p><pre>interface A { default void foo() { System.out.println(&quot;A&quot;); } }<br>interface B { default void foo() { System.out.println(&quot;B&quot;); } }<br>class C implements A, B {<br>    @Override<br>    public void foo() { // Mandatory override<br>        A.super.foo(); // Manual resolution<br>    }<br>}</pre><h3>Problem 2: State Duplication</h3><p>Interfaces can’t encapsulate state, forcing subclasses to repeat fields:</p><pre>// BAD DESIGN: Interface forces duplication<br>interface Engine {<br>    default void start() {<br>        // Can’t access fuelLevel here!<br>    }<br>}<br>class Car implements Engine {<br>    private int fuelLevel; // Duplicated in every Engine implementer<br>}</pre><h3>Key Takeaways: Abstract Class vs Interface</h3><p><strong>Use Interfaces When Use Abstract Classes When </strong>Defining a contract (capabilities).Sharing state or non-public methods.Multiple inheritance is required.Enforcing initialization via constructors.Evolving APIs with default methods.Implementing the template method pattern.Functional programming (lambdas).Providing partial implementation with shared logic.</p><h3>Real-World Example: Java Collections Framework</h3><ul><li><strong>Interface</strong>: List&lt;T&gt; defines behavior (add(), get()).</li><li><strong>Abstract Class</strong>: AbstractList&lt;T&gt; implements common methods (indexOf()).</li><li><strong>Concrete Class</strong>: ArrayList&lt;T&gt; extends AbstractList for array-backed logic.</li></ul><pre>// Simplified example<br>interface List&lt;T&gt; {<br>    void add(T item);<br>    T get(int index);<br>}<br><br>abstract class AbstractList&lt;T&gt; implements List&lt;T&gt; {<br>    protected int size; // Shared state<br>    public int size() { return size; } // Reusable method<br>}<br>class ArrayList&lt;T&gt; extends AbstractList&lt;T&gt; {<br>    private Object[] elements;<br>    @Override<br>    public void add(T item) { /* ... */ }<br>    @Override<br>    public T get(int index) { /* ... */ }<br>}</pre><h3>Conclusion</h3><p>While interfaces with default methods are powerful, <strong>abstract classes remain indispensable</strong> for:</p><ul><li><strong>State management</strong> (instance variables).</li><li><strong>Constructors</strong> to enforce initialization rules.</li><li><strong>Template methods</strong> defining workflows.</li><li><strong>Non-public helpers</strong> (protected/package-private).</li></ul><p><strong>Use interfaces for “what” a class can do</strong> and <strong>abstract classes for “how” it does it</strong>. By combining both, you can write flexible, reusable, and maintainable Java code.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=5e9155a60d1e" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>