Java Abstract Class & Abstract Methods

package Pack1;

abstract class my_abstract5 {
    abstract void my_test();  // Abstract method (no body; ends with semicolon)

    public static void main(String[] args) {
        my_abstract5 obj1 = new my_next();  // Upcasting subclass to abstract reference
        obj1.my_test();
    }
}

class my_next extends my_abstract5 {
    void my_test() {
        System.out.println("Cricket ...");
    }
}

Output:

Cricket ...

1. Five Golden Rules of Java Abstract Classes 🔝

Rule Compiler Enforcement Explanation
No Direct new Compile-time error You cannot instantiate an abstract class directly (new my_abstract5() is illegal).
Abstract Method Host Mandatory abstract class Any class containing at least 1 abstract method must be declared abstract.
Subclass Contract Must override or be abstract A concrete subclass must override every inherited abstract method.
Constructors & State Fully supported Abstract classes can have instance variables, constructors (called via super()), and main().

2. Combining Abstract Methods & Concrete Methods 🔝

Unlike pure Java interfaces (prior to Java 8), an abstract class can mix unimplemented abstract methods with fully implemented concrete helper methods:

abstract class Vehicle {
     // 1. Abstract method: every subclass MUST implement this
    abstract void startEngine();

     // 2. Concrete method: shared directly by all subclasses
    void honkHorn() {
        System.out.println("Beep! Beep!");
    }
}

class Car extends Vehicle {
    void startEngine() {
        System.out.println("Car engine started with key fob.");
    }
}

public class AbstractMixedDemo {
    public static void main(String[] args) {
        Vehicle v = new Car();
        v.startEngine();
        v.honkHorn();
    }
}

Terminal Output:

Car engine started with key fob.
Beep! Beep!

3. Constructors & Instance Fields in an Abstract Class 🔝

Even though you cannot call new Employee(...) directly, an abstract class can define a constructor to initialize shared fields (name, baseSalary) when a concrete subclass calls super(name, baseSalary):

abstract class Employee {
    String name;
    int baseSalary;

     // Abstract class constructor runs via super(...) when a subclass is instantiated
    Employee(String name, int baseSalary) {
        this.name = name;
        this.baseSalary = baseSalary;
    }
    abstract int calculatePay();
}

class Developer extends Employee {
    int bonus;
    Developer(String name, int baseSalary, int bonus) {
        super(name, baseSalary);  // Invokes abstract parent constructor!
        this.bonus = bonus;
    }
    int calculatePay() { return baseSalary + bonus; }
}

public class AbstractConstructorDemo {
    public static void main(String[] args) {
        Employee dev = new Developer("Alex", 80000, 15000);
        System.out.println(dev.name + " Total Pay: " + dev.calculatePay());
    }
}

Terminal Output:

Alex Total Pay: 95000

4. Runtime Polymorphism with an Abstract Array 🔝

You can declare an array or collection of the abstract parent type (Shape[]) and store different concrete subclasses (Circle, Rectangle) inside it:

abstract class Shape {
    abstract double area();
}

class Circle extends Shape {
    double r;
    Circle(double r) { this.r = r; }
    double area() { return 3.14159 * r * r; }
}

class Rectangle extends Shape {
    double w, h;
    Rectangle(double w, double h) { this.w = w; this.h = h; }
    double area() { return w * h; }
}

public class PolymorphicShapes {
    public static void main(String[] args) {
        Shape[] shapes = {new Circle(10), new Rectangle(5, 8)};
        for (Shape s : shapes) {
            System.out.println("Shape area: " + s.area());
        }
    }
}

Terminal Output:

Shape area: 314.159
Shape area: 40.0

5. Multi-Level Abstract Inheritance (Partial Implementation) 🔝

If a subclass implements only some of its parent's abstract methods, that intermediate subclass must also be marked abstract until a leaf class implements the rest:

abstract class BaseParser {
    abstract void openSource();
    abstract void parseRows();
}

 // Partial implementation: still abstract because parseRows() is not implemented yet!
abstract class FileParser extends BaseParser {
    void openSource() { System.out.println("Opened local file stream."); }
}

class CsvParser extends FileParser {
    void parseRows() { System.out.println("Parsed comma-separated rows."); }
}

public class MultiLevelAbstract {
    public static void main(String[] args) {
        BaseParser p = new CsvParser();
        p.openSource();
        p.parseRows();
    }
}

Terminal Output:

Opened local file stream.
Parsed comma-separated rows.

6. Comparison: Abstract Class vs Interface in Java 🔝

Feature abstract class interface
Multiple Inheritance Single class only (extends 1 class) Multiple (implements A, B, C)
Instance Fields (State) Yes (mutable non-static fields) No (only public static final constants)
Constructors Yes (invoked via super()) No constructors allowed
Access Modifiers public, protected, package, private Public API contract (plus private helpers in Java 9+)

7. Production Recipe: The Template Method Design Pattern 🔝

Abstract classes shine when implementing the Template Method pattern: a final method in the abstract parent locks in the workflow steps while delegating customizable steps to abstract hooks:

abstract class DataExporter {
     // Template method (final so subclasses cannot alter the execution sequence)
    public final void export() {
        connect();
        writeData();
        close();
    }
    void connect() { System.out.println("1. Connected to output buffer"); }
    abstract void writeData();
    void close()   { System.out.println("3. Flushed and closed buffer"); }
}

public class PdfExporter extends DataExporter {
    void writeData() { System.out.println("2. Rendered PDF pages"); }
    public static void main(String[] args) {
        new PdfExporter().export();
    }
}

Terminal Output:

1. Connected to output buffer
2. Rendered PDF pages
3. Flushed and closed buffer

8. Common Developer Pitfalls & Traps 🔝

Illegal Modifier Combinations: abstract final or abstract private

An abstract method or class cannot be marked final (which forbids overriding/subclassing), private (which hides the method from subclasses), or static (which belongs to the class rather than an instance). Combining abstract with any of these causes an immediate compile error.

Calling an Overridden Abstract Method Inside the Parent Constructor

Avoid calling an abstract method inside the parent abstract class's constructor, because the subclass's fields have not been initialized yet when super() runs!

9. Complete Compilable Java Program 🔝

public class OopAbstractFullDemo {
    abstract static class Account { abstract int getInterest(); }
    static class Savings extends Account { int getInterest() { return 100; } }
    public static void main(String[] args) {
        if (new Savings().getInterest() == 100) {
            System.out.println("All Java abstract class verification checks passed!");
        }
    }
}

Terminal Output:

All Java abstract class verification checks passed!

10. Frequently Asked Questions (FAQ) 🔝

Can an abstract class have zero abstract methods?

Yes! Declaring a class abstract even when all of its methods have bodies prevents callers from instantiating the base class directly with new.

Can an abstract class have a public static void main(String[] args) method?

Yes, as shown in our first example (my_abstract5). Because main() is static, the JVM can execute java Pack1.my_abstract5 without instantiating my_abstract5.

Can an abstract class implement an interface without implementing all of its methods?

Yes! An abstract class can declare implements Runnable and leave run() unimplemented for its concrete subclasses to provide.

Can I instantiate an abstract class using an anonymous inner class?

Yes: my_abstract5 obj = new my_abstract5() { void my_test() { System.out.println("Inline!"); } }; creates an anonymous concrete subclass on the fly.

When should I choose an abstract class over an interface?

Choose an abstract class when closely related classes need to share non-static instance fields, constructor logic, or protected state; choose an interface to define a capability across unrelated classes.

Further Reading & Related Tutorials 🔝


Java



plus2net.com






✖
We use cookies to improve your browsing experience. . Learn more
HTML MySQL PHP JavaScript ASP Photoshop Articles Contact us
© 2000-2026 plus2net.com All rights reserved worldwide Privacy Policy Disclaimer