The Programmer's Guide
  • About
  • Algorithm
    • Big O Notation
      • Tree
      • Problems
    • Basic Notes
    • Data Structure Implementation
      • Custom LinkedList
      • Custom Stack
      • Custom Queue
      • Custom Tree
        • Binary Tree Implementation
        • Binary Search Tree Implementation
        • Min Heap Implementation
        • Max Heap Implementation
        • Trie Implementation
      • Custom Graph
        • Adjacency List
        • Adjacency Matrix
        • Edge List
        • Bidirectional Search
    • Mathematical Algorithms
      • Problems - Set 1
      • Problems - Set 2
    • Bit Manipulation
      • Representation
      • Truth Tables
      • Number System
        • Java Program
      • Problems - Set 1
    • Searching
    • Sorting
    • Array Algorithms
    • String Algorithms
    • Tree
      • Tree Traversal Techniques
      • Tree Implementation
      • Applications of Trees
      • Problems - Set 1
    • Graph
      • Graph Traversal Techniques
      • Shortest Path Algorithms
      • Minimum Spanning Tree (MST) Algorithms
    • Dynamic Programming
      • Problems - Set 1
    • Recursion
    • Parallel Programming
    • Miscellaneous
      • Problems - Set 1
  • API
    • API Basics
      • What is an API?
      • Types of API
        • Comparison - TBU
      • Synchronous vs Asynchronous API
    • API Architecture
      • Synchronous & Asynchronous Communication
    • API Specification
  • Cloud Computing
    • Cloud Fundamentals
      • Cloud Terminology
      • Core Terminology
      • Cloud Models
      • Cloud Service Models
      • Benefits, Challenges and Risk of Cloud Computing
      • Cloud Ecosystem
  • Database
    • DBMS
      • Types of DBMS
        • Relational DBMS (RDBMS)
        • NoSQL DBMS
        • Object-Oriented DBMS (OODBMS)
        • Columnar DBMS
        • In-Memory DBMS
        • Distributed DBMS
        • Cloud-Based DBMS
        • Hierarchical DBMS
      • DBMS Architecture
      • DBMS Structure
    • SQL Databases
      • Terminology
      • RDBMS Concepts
        • Entity Relationship Diagram (ERD)
          • ERD Examples
        • Normalization
        • Denormalization
        • ACID & BASE Properties
          • ACID Properties
          • BASE Properties
        • Locking and Unlocking
      • SQL Fundamentals
        • SQL Commands
          • DDL (Data Definition Language)
          • DML (Data Manipulation Language)
          • DCL (Data Control Language)
          • TCL (Transaction Control Language)
          • DQL (Data Query Language)
        • SQL Operators
          • INTERSECT
          • EXCEPT
          • MINUS
          • IN and NOT IN
          • EXISTS and NOT EXISTS
        • SQL Clauses
          • Joins
          • OVER
          • WITH
          • CONNECT BY
          • MODEL
          • FETCH FIRST
          • KEEP
          • OFFSET with FETCH
        • SQL Functions
          • Oracle Specific
        • SQL Data Types
          • Numeric Types
          • Character Types
          • Date & Time Types
          • Large Object Types
        • Others
          • Indexing
      • Vendor Specific Concepts
        • Oracle Specific
          • Data Types
          • Character Set
          • Rownum, Rowid, Urowid
          • Order of Execution of the query
          • Keys
          • Tablespace
          • Partition
      • Best Practice
      • Resources & References
        • O’Reilly SQL Cookbook (2nd Edition)
          • 1. Retrieving Records
          • 2. Sorting Query Results
          • 3. Working with Multiple Tables
          • 4. Inserting, Updating, and Deleting
          • 5. Metadata Queries
          • 6. Working with Strings
          • 7. Working with Numbers
          • 8. Date Arithmetic
          • 9. Date Manipulation
          • 10. Working with Ranges
          • 11. Advanced Searching
          • 12. Reporting and Reshaping
          • 13. Hierarchical Queries
          • 14. Odds 'n' Ends
    • SQL vs NoSQL
    • Best Practices
  • Git
    • Commands
      • Setup and Configuration Commands
      • Getting and Creating Projects
      • Tracking Changes
      • Branching and Merging
      • Sharing and Updating Projects
      • Inspection and Comparison
      • Debugging
      • Patching
      • Stashing and Cleaning
      • Advanced Manipulations
    • Workflows
      • Branching Strategies
        • Git Flow
        • Trunk-Based Development
        • GitHub Flow
        • Comparison
      • Merge Strategies
        • Merge
        • Rebase
        • Squash
        • Fast-forward vs No-fast-forward
        • MR vs PR
      • Conflict Resolution
        • Handling Merge Conflicts
        • Merge Conflicts
        • Rebase Conflicts
        • Divergent Branches After git pull
        • Force Push
      • Patch & Recovery
        • Cherry-pick strategies
        • Revert vs Reset
        • Recover from a bad rebase
      • Rebasing Practices
        • Merge vs Rebase
        • Rebase develop branch on main branch
      • Repository Management
        • Working Directory
        • Mirror a repository
        • Convert a local folder to a Git repo
        • Backup and restore a Git repository
  • Java
    • Java Installation
    • Java Distributions
    • Java Platform Editions
      • Java SE
      • Java EE
      • Jakarta EE
      • Java ME
      • JavaFX
    • Java Overview
      • OOP Principles
        • Encapsulation
        • Inheritance
        • Polymorphism
        • Abstraction
          • Abstract Class & Method
          • Interface
            • Functional Interfaces
            • Marker Interfaces
          • Abstract Class vs Interface
      • OOP Basics
        • What is a Class?
          • Types of Classes
        • What is an Object?
          • Equals and HashCode
            • FAQ
          • Shallow Copy and Deep Copy
          • Ways to Create Object
          • Serialization & Deserialization
        • Methods & Fields
          • Method Overriding & Overloading
          • Method Signature & Header
          • Variables
        • Constructors
        • Access Modifiers
      • Parallelism & Concurrency
        • Ways to Identify Thread Concurrency or Parallelism
        • Thread Basics
          • Thread vs Process
          • Creating Threads
          • Thread Context Switching
          • Thread Lifecycle & States
          • Runnable & Callable
          • Types of Threads
          • Thread Priority
        • Thread Management & Synchronisation
          • Thread Resource Sharing
          • Thread Synchronization
            • Why is Synchronization Needed?
            • Synchronized Blocks & Methods
          • Thread Lock
            • Types of Locks
            • Intrinsic Lock (Monitor Lock)
            • Reentrant Lock
          • Semaphore
          • Thread Starvation
          • Thread Contention
          • Thread Deadlock
          • Best Practices for Avoiding Thread Issues
      • Keywords
        • this
        • super
        • Access Modifiers
      • Data Types
        • Default Values
        • Primitive Types
          • byte
          • short
          • int
          • long
          • float
          • double
          • char
          • boolean
        • Non-Primitive (Reference) Types
          • String
            • StringBuilder
            • StringBuffer
              • Problems
            • Multiline String
            • Comparison - String, StringBuilder & StringBuffer
          • Array
          • Collections
            • List
              • Array vs List
              • ArrayList
              • Vector
                • Stack
                  • Problems
              • LinkedList
            • Queue
              • PriorityQueue
              • Deque (Double-Ended Queue)
                • ArrayDeque
                • ConcurrentLinkedDeque - TBU
                • LinkedBlockingDeque - TBU
            • Map
              • HashMap
              • Hashtable
              • LinkedHashMap
              • ConcurrentHashMap
              • TreeMap
              • EnumMap
              • WeakHashMap
            • Set
              • HashSet
              • LinkedHashSet
              • TreeSet
              • EnumSet
              • ConcurrentSkipListSet
              • CopyOnWriteArraySet
        • Specialized Classes
          • BigInteger
          • BigDecimal
            • Examples
          • BitSet
          • Date and Time
            • Examples
          • Optional
          • Math
          • UUID
          • Scanner
          • Formatter
            • Examples
          • Properties
          • Regex (Pattern and Matcher)
            • Examples
          • Atomic Classes
          • Random
          • Format
            • NumberFormat
            • DateFormat
            • DecimalFormat
        • Others
          • Object
          • Enum
            • Pre-Defined Enum
            • Custom Enum
            • EnumSet and EnumMap
          • Record
          • Optional
          • System
          • Runtime
          • ProcessBuilder
          • Class
          • Void
          • Throwable
            • Error
            • Exception
              • Custom Exception Handling
              • Best Practice
            • Error vs Exception
            • StackTraceElement
    • Java Features by Version
      • How New Java Features are Released ?
      • Java Versions
        • Java 8
        • Java 9
        • Scoped Values
        • Unnamed Variables & Patterns
      • FAQ
    • Concepts
      • Set 1
        • Streams
          • flatmap
          • Collectors Utility Class
          • Problems
        • Functional Interfaces
          • Standard Built-In Interfaces
          • Custom Interfaces
        • Annotation
          • Custom Annotation
          • Meta Annotation
        • Generics
          • Covariance and Invariance
        • Asynchronous Computation
          • Future
          • CompletableFuture
          • Future v/s CompletableFuture
          • ExecutorService
            • Thread Pool
            • Types of Work Queues
            • Rejection Policies
            • ExecutorService Implementations
            • ExecutorService Usage
          • Locks, Atomic Variables, CountDownLatch, CyclicBarrier - TBU
          • Parallel Streams, Fork/Join Framework,Stream API with Parallelism - TBU
      • Set 2
        • Standards
          • ISO Standards
          • JSR
            • JSR 303, 349, 380 (Bean Validation)
        • Operator Precedence
      • Set 3
        • Date Time Formatter
        • Validation
      • Set 4
        • Input from User
        • Comparison & Ordering
          • Object Equality Check
          • Comparable and Comparator
            • Comparator Interface
          • Sorting of Objects
          • Insertion Ordering
    • Packages
      • Core Packages
        • java.lang
          • java.lang.System
          • java.lang.Thread
      • Jakarta Packages
        • jakarta.validation
        • javax.validation
      • Third-party Packages
    • Code Troubleshoot
      • Thread Dump
      • Heap Dump
    • Code Quality & Analysis
      • ArchUnit
      • Terminologies
        • Cyclic dependencies
    • Code Style
      • Naming Convention
      • Package Structure
      • Formatting
      • Comments and Documentation
      • Imports
      • Exception Handling
      • Class Structure
      • Method Guidelines
      • Page 1
      • Code Smells to Avoid
      • Lambdas and Streams Style
      • Tools
    • Tools
      • IntelliJ IDEA
        • Shortcuts for MAC
      • Apache JMeter
        • Examples
      • Thread Dump Capture
        • jstack
        • VisualVM - TBU
        • jcmd - TBU
        • JConsole - TBU
        • YourKit Java Profiler - TBU
        • Eclipse MAT - TBU
        • IntelliJ IDEA Profiler - TBU
        • AppDynamics - TBU
        • Dynatrace - TBU
        • Thread Dump Analyzers - TBU
      • Heap Dump Capture
        • jmap
        • VisualVM - TBU
        • jcmd - TBU
        • Eclipse MAT (Memory Analyzer Tool) - TBU
        • IntelliJ IDEA Profiler - TBU
        • YourKit Java Profiler - TBU
        • AppDynamics - TBU
        • Dynatrace - TBU
        • Kill -3 Command - TBU
        • jhat (Java Heap Analysis Tool) - TBU
        • JVM Options - TBU
      • Wireshark
        • Search Filters
    • Best Practices
      • Artifact and BOM Versioning
  • Maven
    • Installation
    • Local Repository & Configuration
    • Command-line Options
    • Build & Lifecycle
    • Dependency Management
      • Dependency
        • Transitive Dependency
        • Optional Dependency
      • Dependency Scope
        • Maven Lifecycle and Dependency Scope
      • Dependency Exclusions & Overrides
      • Bill of Materials (BOM)
      • Dependency Conflict Resolution
      • Dependency Tree & Analysis
      • Dependency Versioning Strategies
    • Plugins
      • Build Lifecycle Management
      • Dependency Management
      • Code Quality and Analysis
      • Documentation Generation
      • Code Generation
      • Packaging and Deployment
      • Reporting
      • Integration and Testing
      • Customization and Enhancement
        • build-helper-maven-plugin
        • properties-maven-plugin
        • ant-run plugin
        • exec-maven-plugin
        • gmavenplus-plugin
      • Performance Optimization
    • FAQs
      • Fixing Maven SSL Issues: Unable to Find Valid Certification Path
  • Spring
    • Spring Basics
      • What is Spring?
      • Why Use Spring
      • Spring Ecosystem
      • Versioning
      • Setting Up a Spring Project
    • Core Concepts
      • Spring Core
        • Dependency Injection (DI)
        • Stereotype Annotation
      • Spring Beans
        • Bean Lifecycle
        • Bean Scope
          • Singleton Bean
        • Lazy & Eager Initialization
          • Use Case of Lazy Initialization
        • BeanFactory
        • ApplicationContext
      • Spring Annotations
        • Spring Boot Specific
        • Controller Layer (Web & REST Controllers)
    • Spring Features
      • Auto Configuration
        • Spring Boot 2: spring.factories
        • Spring Boot 3: spring.factories
      • Spring Caching
        • In-Memory Caching
      • Spring AOP
        • Before Advice
        • After Returning Advice
        • After Throwing Advice
        • After (finally) Advice
        • Around Advice
      • Spring File Handling
      • Reactive Programming
        • Reactive System
        • Reactive Stream Specification
        • Project Reactor
          • Mono & Flux
      • Asynchronous Computation
        • @Async annotation
      • Spring Security
        • Authentication
          • Core Components
            • Security Filter Chain
              • HttpSecurity
              • Example
            • AuthenticationManager
            • AuthenticationProvider
            • UserDetailsService
              • UserDetails
              • PasswordEncoder
            • SecurityContext
            • SecurityContextHolder
            • GrantedAuthority
            • Security Configuration (Spring Security DSL)
          • Authentication Models
            • One-Way Authentication
            • Mutual Authentication
          • Authentication Mechanism
            • Basic Authentication
            • Form-Based Authentication
            • Token-Based Authentication (JWT)
            • OAuth2 Authentication
            • Multi-Factor Authentication (MFA)
            • SAML Authentication
            • X.509 Certificate Authentication
            • API Key Authentication
            • Remember-Me Authentication
            • Custom Authentication
          • Logout Handling
        • Authorization
        • Security Filters and Interceptors
        • CSRF
          • Real-World CSRF Attacks & Prevention
        • CORS
        • Session Management and Security
        • Best Practices
      • Spring Persistence
        • JDBC
          • JDBC Components
          • JDBC Template
          • Transaction Management
          • Best Practices in JDBC Usage
          • Datasource
            • Connection Pooling
              • HikariCP
            • Caching
        • JPA (Java Persistence API)
          • JPA Fundamentals
          • ORM Mapping Annotations
            • 1. Entity and Table Mappings
            • 2. Field/Column Mappings
            • 3. Relationship Mappings
            • 4. Inheritance Mappings
            • 5. Additional Configuration Annotations
          • Querying Data
            • JPQL
            • Criteria API
            • JPA Specification
              • Example - Employee Portal
            • Native SQL Queries
            • Named Queries
            • Query Return Types
            • Pagination & Sorting
              • Example - Employee Portal
            • Projection
          • Fetch Strategies in JPA
        • JPA Implementation
          • Hibernate
            • Properties
            • Example
        • Spring Data JPA
          • Repository Abstractions
          • Entity-to-Table Mapping
          • Derived Query Methods
        • Cross-Cutting Concerns
          • Transactions
          • Caching
          • Concurrency
        • Examples
          • Employee Portal
            • API
    • Distributed Systems & Communication
      • Distributed Scheduling
      • Inter-Service Communication
        • 1. RestTemplate
        • 2. WebClient
        • 3. OpenFeign
        • Retry Mechanism
          • @Retryable annotation
            • Example
    • Security & Data Protection
      • Encoding | Decoding
        • Types
          • Base Encoding
            • Base16 - TBD
              • Encoding and Decoding in Java - TBD
            • Base32
              • Encoding and Decoding in Java
            • Base64 -TBD
              • Encoding and Decoding in Java - TBD
          • Text Encoding - TBD
            • Extended ASCII
              • Encoding and Decoding in Java - TBD
                • ISO-8859-1
                • Windows-1252 - TBD
                • IBM Code Pages - TBD
            • ASCII
              • Encoding and Decoding in Java
        • Java Guidelines
          • Text Encoding Decoding Examples
          • Base Encoding Decoding Examples
          • Best Practices and Concepts
          • Libraries
      • Cryptography
        • Terminology
        • Java Cryptography Architecture (JCA)
        • Key Management
          • Key Generation
            • Tools and Libraries
              • OpenSSL
              • Java Keytool
                • Concept
                • Use Cases
            • Key & Certificate File Formats
          • Key Distribution
          • Key Storage
          • Key Rotation
          • Key Revocation
        • Encryption & Decryption
          • Symmetric Encryption
            • Algorithm
            • Modes of Operation
            • Examples
          • Asymmetric Encryption
            • Algorithm
            • Mode of Operation
            • Examples
    • Utilities & Libraries
      • Apache Libraries
        • Apache Camel
          • Camel Architecture
            • Camel Context
            • Camel Endpoints
            • Camel Components
            • Camel Exchange & MEP
          • Spring Dependency
          • Different Components
            • Camel SFTP
        • Apache Commons Lang
      • MapStruct Mapper
      • Utilities by Spring framework
        • FileCopyUtils
    • General Concepts
      • Spring Boot Artifact Packaging
      • Classpath and Resource Loading
      • Configuration - Mapping Properties to Java Class
      • Validations in Spring Framework
        • Jakarta Validation
          • Jakarta Bean Validation Annotations
    • Practical Guidelines
      • Spring Configuration
      • Spring Code Design
  • Software Testing
    • Software Testing Methodologies
      • Functional Testing
      • Non Functional Testing
    • Software Testing Life Cycle (STLC)
    • Integration Test
      • Dynamic Property Registration
    • Java Test Framework
      • JUnit
        • JUnit 4
          • Examples
        • JUnit 5
          • Examples
        • JUnit 4 vs JUnit 5
  • System Design
    • Foundations
      • Programming Paradigms
      • Object-Oriented Design
        • SOLID Principles
        • GRASP Principles
        • Composition
        • Aggregation
        • Association
      • Design Pattern
        • Creational Pattern
        • Structural Pattern
        • Behavioral Pattern
        • Examples
          • Data Collector
          • Payment Processor
        • Design Enhancements
          • Fluent API Design
            • Examples
    • Architectural Building Blocks
      • CAP Theorem
      • Load Balancer
        • Load Balancer Architecture
        • Load Balancing in Java Microservices
          • Client-Side Load Balancing Example
          • Server-Side Load Balancing Example
        • Load Balancer Monitoring Tool
      • Scaling
        • Vertical Scaling (Scaling Up)
        • Horizontal Scaling (Scaling Out)
        • Auto-Scaling
        • Database Scaling via Sharding
      • Caching
        • Pod-Level vs Distributed Caching
      • Networking Metrics
        • Types of Delay
        • Scenario
      • System Characteristics
      • Workload Types
      • Resilience & Failure Handling
    • Performance
      • Why Is My API Sometimes Slow ?
    • Security
      • Security by Design
      • Zero Trust Security Model
      • Zero Trust Architecture
      • Principles
        • CIA
        • Least Privilege Principle
        • Defense in Depth
      • Security Threats & Mitigations
        • OWASP
          • Top 10 Security Threats
          • Application Security Verification Standard
          • Software Assurance Maturity Model
          • Dependency Check
          • CSRFGuard
          • Cheat Sheets
          • Security Testing Guide
          • Threat Dragon
        • Threat Modeling
      • Compliance & Regulation
        • PCI DSS
    • Deployment Patterns
    • Diagrams
      • UML Diagrams
        • PlantUML
          • Class Diagram
          • Object Diagram
          • Sequence Diagram
          • Use Case Diagram
          • Activity Diagram
          • State Diagram
          • Architecture Diagram
          • Component Diagram
          • Timing Diagram
          • ER Diagram (Entity-Relationship)
          • Network Diagram
    • Common Terminologies
    • Problems
      • Reference Materials
      • Cache Design
  • Interview Guide
    • Non-Technical
      • Behavioural or Introductory Guide
      • Project Specific
    • Technical
      • Java Interview Companion
        • Java Key Concepts
          • Set 1
          • Set 2
        • Java Code Snippets
        • Java Practice Programs
          • Set 3 - Strings
          • Set 4 - Search
          • Set 5 - Streams and Collection
      • SQL Interview Companion
        • SQL Practice Problems
          • Set 1
      • Spring Interview Companion
        • Spring Key Concepts
          • Set 1 - General
          • Set 2 - Core Spring
        • Spring Code Snippets
          • JPA
      • Application Server
      • Maven
      • Containerized Application
      • Microservices
    • General
      • Applicant Tracking System (ATS)
      • Flowchart - How to Solve Coding Problem?
Powered by GitBook
On this page
  • About
  • Abstract Keyword
  • Abstract Methods
  • Non-Abstract Methods
  • Instantiation
  • Access Modifier
  • 1. public Modifier
  • 2. protected Modifier
  • 3. default (Package-Private) Modifier
  • 4. private Modifier
  • Example
  • Constructors in Abstract Classes
  • Static Methods in Abstract Classes
  • Nested Abstract Class
  • Abstract Classes and Dependency Injection
  • Abstract Classes in Design Patterns
  • Template Method Pattern
  • Factory Method Pattern
  • Adapter Pattern
  • Abstract Class with multiple inheritance

Was this helpful?

  1. Java
  2. Java Overview
  3. OOP Principles
  4. Abstraction

Abstract Class & Method

About

An abstract class in Java is a class that cannot be instantiated directly, meaning we cannot create objects of an abstract class using the new keyword. Instead, it serves as a blueprint for other classes and may contain both abstract and concrete methods.

Rules for Abstract Classes:

  1. If a class contains at least one abstract method, it must be declared as abstract.

  2. Abstract methods cannot have a body (implementation) and end with a semicolon (;).

  3. Abstract classes cannot be instantiated directly with the new keyword.

  4. Subclasses of an abstract class must either provide implementations for all abstract methods or be declared abstract themselves.

  5. Subclasses are not required to override non-abstract methods but can choose to if they need to alter the default behavior provided in the abstract class. This enables polymorphic behavior while maintaining flexibility for subclasses.

  • Thread is not a abstract class.

  • Opposite of Abstract class is concrete class.

  • Abstract class supports multilevel inheritance. Note that Java does not support multiple inheritance with classes, but it supports multilevel inheritance.

Partial Implementation: Abstract classes allow partial implementation, where a class can have both abstract (unimplemented) and concrete (implemented) methods. This flexibility provide default behaviors while enforcing that subclasses implement specific methods.

Abstract Keyword

An abstract class or method is declared using the abstract keyword before the class name.

// Abstract class
public abstract class Shape {
    // Abstract method
    public abstract double area();

    // Concrete method
    public void display() {
        System.out.println("This is a shape.");
    }
}

Abstract Methods

Abstract methods are method declarations that don't have a body (implementation). They are declared using the abstract keyword before the method return type. Subclasses that inherit/extends from the abstract class must provide implementations for all inherited abstract methods. Abstract methods define the functionality that subclasses must adhere to, promoting a common interface within the class hierarchy.

// Abstract class with abstract method
abstract class AbstractShape {
    // Abstract method without implementation
    public abstract double area();
}

// Concrete subclass implementing AbstractShape
class Circle extends AbstractShape {
    private double radius;

    public Circle(double radius) {
        this.radius = radius;
    }

    // Implementing abstract method
    @Override
    public double area() {
        return Math.PI * radius * radius;
    }
}

Non-Abstract Methods

Abstract classes can also have concrete methods (methods with a body) that provide default implementations for common functionalities. Subclasses can inherit and potentially override these methods to customize behavior.

// Abstract class with both abstract and concrete methods
abstract class AbstractShape {
    // Abstract method without implementation (must be implemented by subclasses)
    public abstract double area();

    // Concrete method with implementation
    public void display() {
        System.out.println("This is a shape.");
    }
}

// Concrete subclass implementing AbstractShape
class Circle extends AbstractShape {
    private double radius;

    public Circle(double radius) {
        this.radius = radius;
    }

    // Implementing abstract method
    @Override
    public double area() {
        return Math.PI * radius * radius;
    }

    // Overriding concrete method from AbstractShape
    @Override
    public void display() {
        System.out.println("This is a circle with radius: " + radius);
    }
}

// Main class to test
public class Main {
    public static void main(String[] args) {
        AbstractShape shape = new Circle(5.0);

        // Calls overridden method from Circle
        shape.display();  
        
        // Calls implemented abstract method
        System.out.println("Area: " + shape.area());  
    }
}

Instantiation

We cannot create objects directly from an abstract class using the new keyword. Subclasses, which are not abstract, can be instantiated.

// Abstract class
abstract class AbstractShape {
    // Abstract method without implementation
    public abstract double area();
}

// Main class
public class Main {
    public static void main(String[] args) {
        // Cannot instantiate AbstractShape directly
        // AbstractShape shape = new AbstractShape(); // Error: Cannot instantiate abstract class

        // But can use polymorphism with concrete subclasses
        AbstractShape circle = new Circle(5);
        System.out.println("Area of circle: " + circle.area());
    }
}

Access Modifier

Access Modifiers control the visibility and accessibility of classes, methods, and fields. Abstract classes leverage access modifiers to encapsulate certain methods or fields, making them accessible only to specific parts of the program. This capability is useful in complex hierarchies where we want to limit access to certain parts of the abstract class.

1. public Modifier

Abstract classes and methods can use the public modifier to allow maximum visibility. For example, if an abstract method needs to be implemented across packages, it should be declared public in the abstract class.

2. protected Modifier

protected methods in an abstract class can only be accessed within the same package or by subclasses in other packages. This is useful for methods that should only be available to subclasses but hidden from other classes.

3. default (Package-Private) Modifier

The package-private (default) modifier restricts visibility to within the same package. In an abstract class, a method declared with no access modifier can only be accessed by classes within the same package.

4. private Modifier

In Java, private is not allowed for methods declared in an abstract class because it would make them inaccessible to subclasses. However, private fields can be used in abstract classes and are accessible only within the class itself.

We can have private concrete methods. It can be used to share common code between concrete methods.

Example

AbstractShape class

// Abstract class with public, protected, private, and default members
abstract class AbstractShape {
    private String shapeName = "Shape"; // Private variable (accessible only within this class)
    protected String type = "Generic";  // Protected variable (accessible in subclasses)
    double size = 0.0;                  // Default (package-private) variable
    public String somePublic = "Public Variable"; // Public variable

    // Public constructor
    public AbstractShape() {
        System.out.println("AbstractShape Constructor Called");
    }

    // Abstract method (must be implemented by subclasses)
    public abstract double area();

    // Concrete method (can be overridden)
    public void display() {
        System.out.println("This is a " + shapeName);
    }

    // Private method (not inherited by subclasses)
    private void privateMethod() {
        System.out.println("Private method in AbstractShape");
    }

    // Protected method (can be accessed in subclasses)
    protected void protectedMethod() {
        System.out.println("Protected method in AbstractShape");
    }

    // Default method (accessible within the same package)
    void defaultMethod() {
        System.out.println("Default method in AbstractShape");
    }
}

Circle Class

// Concrete subclass extending AbstractShape
class Circle extends AbstractShape {
    private double radius;  // Private variable

    // Public constructor
    public Circle(double radius) {
        this.radius = radius;
        this.type = "Circle"; // Accessing protected variable from AbstractShape
    }

    // Implementing the abstract method
    @Override
    public double area() {
        return Math.PI * radius * radius;
    }

    // Overriding a concrete method
    @Override
    public void display() {
        System.out.println("This is a " + type + " with radius: " + radius);
    }

    // Overriding a protected method
    @Override
    protected void protectedMethod() {
        System.out.println("Protected method overridden in Circle");
    }

    // Overriding a default method
    @Override
    void defaultMethod() {
        System.out.println("Default method overridden in Circle");
    }
}

Square class

// Another subclass to demonstrate inheritance
class Square extends AbstractShape {
    private double side;

    public Square(double side) {
        this.side = side;
        this.type = "Square";
    }

    @Override
    public double area() {
        return side * side;
    }

    @Override
    public void display() {
        System.out.println("This is a " + type + " with side length: " + side);
    }
}

Main Class

// Main class to test
public class Main {
    public static void main(String[] args) {
        AbstractShape circle = new Circle(5.0);
        AbstractShape square = new Square(4.0);

        // Accessing public methods
        circle.display();  
        square.display();

        // Calling overridden method
        System.out.println("Circle Area: " + circle.area());
        System.out.println("Square Area: " + square.area());

        // Accessing protected and default methods (only within the package)
        if (circle instanceof Circle) {
            ((Circle) circle).protectedMethod();
            ((Circle) circle).defaultMethod();
        }
        
        /* Output:
        AbstractShape Constructor Called
        AbstractShape Constructor Called
        This is a Circle with radius: 5.0
        This is a Square with side length: 4.0
        Circle Area: 78.53981633974483
        Square Area: 16.0
        Protected method overridden in Circle
        Default method overridden in Circle
        */
    }
}

Constructors in Abstract Classes

While abstract classes cannot be instantiated directly, they can have constructors. These constructors are primarily used to initialize fields or perform setup tasks that are common across all subclasses. When a subclass of an abstract class is instantiated, the constructor of the abstract class is called as part of the instantiation chain.

This feature is essential because it allows abstract classes to set up necessary state or dependencies that subclasses rely on. Additionally, since subclasses must call the constructor of the abstract superclass, this approach provides consistency in initialization.

Constructors in abstract classes can have all four access modifiers: public, protected, default , private . However, abstract classes cannot be instantiated directly, so their constructors are used only by subclasses.

  • The public constructor is accessible everywhere, allowing subclasses to call it.

  • The protected constructor can be accessed by subclasses even if they are in different packages.

  • The default constructor is accessible only within the same package.

  • A private constructor in an abstract class makes it impossible for any subclass to instantiate it. It can be used to prevent subclassing while still allowing static methods or singleton-like behavior.

abstract class Account {
    protected double balance;

    // Constructor to initialize balance
    public Account(double balance) {
        this.balance = balance;
        System.out.println("Account created with balance: " + balance);
    }

    // Abstract method to be implemented by subclasses
    public abstract void withdraw(double amount);
}

class SavingsAccount extends Account {
    public SavingsAccount(double balance) {
        super(balance);  // Calls the constructor in the abstract superclass
    }

    @Override
    public void withdraw(double amount) {
        if (balance >= amount) {
            balance -= amount;
            System.out.println("Withdrew: " + amount + ", New balance: " + balance);
        } else {
            System.out.println("Insufficient funds.");
        }
    }
}

Abstract classes can have protected constructors, a technique used to control instantiation and ensure subclasses inherit but cannot create instances directly outside their package.

Here, the protected constructor in BaseComponent prevents instantiation from outside the class hierarchy, emphasizing that this class is intended solely for inheritance.

abstract class BaseComponent {
    protected BaseComponent() {
        System.out.println("BaseComponent constructor");
    }
    public abstract void render();
}

class Button extends BaseComponent {
    @Override
    public void render() {
        System.out.println("Rendering Button");
    }
}

Other Example

// Abstract class with multiple constructors
abstract class Animal {

    // Public Constructor
    public Animal() {
        System.out.println("Public Constructor: Animal Created");
    }

    // Protected Constructor
    protected Animal(String name) {
        System.out.println("Protected Constructor: Animal Name - " + name);
    }

    // Default (package-private) Constructor
    Animal(int age) {
        System.out.println("Default Constructor: Animal Age - " + age);
    }

    // Private Constructor (Cannot be accessed by subclasses)
    private Animal(boolean isWild) {
        System.out.println("Private Constructor: Animal Wild - " + isWild);
    }
}

// Subclass extending Animal
class Dog extends Animal {

    // Calls the public constructor
    public Dog() {
        super(); // Calls Animal()
        System.out.println("Dog Constructor: Dog Created");
    }

    // Calls the protected constructor
    public Dog(String name) {
        super(name); // Calls Animal(String)
        System.out.println("Dog Constructor: Dog Named " + name);
    }

    // Calls the default constructor
    public Dog(int age) {
        super(age); // Calls Animal(int)
        System.out.println("Dog Constructor: Dog Age " + age);
    }
}

// Another level of inheritance (Multilevel)
class Puppy extends Dog {

    public Puppy() {
        super("Tommy"); // Calls Dog(String) -> Animal(String)
        System.out.println("Puppy Constructor: Puppy Created");
    }
}

public class Main {
    public static void main(String[] args) {
        System.out.println("---- Creating Dog with public constructor ----");
        Dog dog1 = new Dog(); 

        System.out.println("\n---- Creating Dog with protected constructor ----");
        Dog dog2 = new Dog("Buddy");

        System.out.println("\n---- Creating Dog with default constructor ----");
        Dog dog3 = new Dog(5);

        System.out.println("\n---- Creating Puppy (Multilevel Inheritance) ----");
        Puppy puppy = new Puppy();

        // ❌ Uncommenting the below line will cause a compilation error because the private constructor is not accessible
        // Animal animal = new Animal(true);
        
        /* Output:
        ---- Creating Dog with public constructor ----
        Public Constructor: Animal Created
        Dog Constructor: Dog Created
        
        ---- Creating Dog with protected constructor ----
        Protected Constructor: Animal Name - Buddy
        Dog Constructor: Dog Named Buddy
        
        ---- Creating Dog with default constructor ----
        Default Constructor: Animal Age - 5
        Dog Constructor: Dog Age 5
        
        ---- Creating Puppy (Multilevel Inheritance) ----
        Protected Constructor: Animal Name - Tommy
        Dog Constructor: Dog Named Tommy
        Puppy Constructor: Puppy Created
        */
    }
}

Static Methods in Abstract Classes

Static methods belong to the class itself rather than to any specific instance. In abstract classes, static methods can provide utility functions or helper methods relevant to the class as a whole. Because static methods do not depend on an instance, they’re often used to perform operations that do not require access to non-static fields of the class.

Since abstract classes can contain both static methods and abstract methods, this structure is more versatile than interfaces (which traditionally only contained abstract methods prior to Java 8).

abstract class MathOperation {
    // Static utility method
    public static int add(int a, int b) {
        return a + b;
    }

    // Abstract method for other operations
    public abstract int operate(int a, int b);
}

class MultiplyOperation extends MathOperation {
    @Override
    public int operate(int a, int b) {
        return a * b;
    }
}

public class Main {
    public static void main(String[] args) {
        // Using static method in the abstract class
        int sum = MathOperation.add(5, 10);
        System.out.println("Sum: " + sum);

        // Using subclass to perform specific operation
        MathOperation operation = new MultiplyOperation();
        int product = operation.operate(5, 10);
        System.out.println("Product: " + product);
    }
}

Nested Abstract Class

Abstract class in Java can contain inner abstract classes, inner concrete classes, and static methods within it.

An inner class is defined within the scope of an outer class. Java supports different types of inner classes, which can also be abstract or concrete:

  • Non-static Inner Class (Instance Inner Class): Tied to an instance of the outer class. It has access to the outer class’s instance members.

  • Static Inner Class: Similar to a regular class but nested within an outer class. It doesn’t require an instance of the outer class to be instantiated and can only access static members of the outer class.

Types of Inner Classes

  • Abstract Inner Class: Defines an abstract class within an outer class, requiring subclasses (either nested or external) to implement its methods.

  • Concrete Inner Class: Provides a fully implemented inner class that can operate within the context of the outer class.

abstract class OuterAbstract {
    // Abstract inner class
    abstract class InnerAbstract {
        public abstract void abstractMethod();
    }

    // Concrete inner class
    class InnerConcrete {
        public void concreteMethod() {
            System.out.println("Concrete method in InnerConcrete class.");
        }
    }

    // Static method
    public static void staticMethod() {
        System.out.println("Static method in OuterAbstract class.");
    }
}

public class Main {
    public static void main(String[] args) {
        // Accessing static method
        OuterAbstract.staticMethod(); // Output: Static method in OuterAbstract class.

        // Creating instance of concrete inner class
        OuterAbstract outer = new OuterAbstract() {
            // Anonymous subclass of OuterAbstract
        };
        OuterAbstract.InnerConcrete innerConcrete = outer.new InnerConcrete();
        innerConcrete.concreteMethod(); // Output: Concrete method in InnerConcrete class.

        // Creating instance of abstract inner class (needs to be extended)
        OuterAbstract.InnerAbstract innerAbstract = outer.new InnerAbstract() {
            @Override
            public void abstractMethod() {
                System.out.println("Abstract method implementation in InnerAbstract class.");
            }
        };
        innerAbstract.abstractMethod(); // Output: Abstract method implementation in InnerAbstract class.
    }
}
class OuterClass {
    private String message = "Hello from OuterClass";

    // Abstract inner class
    abstract class InnerAbstract {
        public abstract void displayMessage();

        // Non-abstract method in the abstract inner class
        public void commonInnerMethod() {
            System.out.println("This is a common method in an abstract inner class.");
        }
    }

    // Concrete subclass of InnerAbstract within the same outer class
    class InnerConcrete extends InnerAbstract {
        @Override
        public void displayMessage() {
            System.out.println("Message from InnerConcrete: " + message);
        }
    }
}

public class Main {
    public static void main(String[] args) {
        OuterClass outer = new OuterClass();
        OuterClass.InnerConcrete inner = outer.new InnerConcrete();
        inner.displayMessage(); // Output: Message from InnerConcrete: Hello from OuterClass
        inner.commonInnerMethod(); // Output: This is a common method in an abstract inner class.
    }
}

Abstract Classes and Dependency Injection

Abstract classes can serve as base types in dependency injection (DI) configurations in frameworks such as Spring. They can provide foundational, unchanging methods while enforcing specific functionalities in subclasses.

public abstract class AbstractService {
    public void logServiceCall() { System.out.println("Service Call Logged"); }
    public abstract void executeService();
}

@Service
public class UserService extends AbstractService {
    @Override
    public void executeService() { System.out.println("Executing user service"); }
}

Abstract Classes in Design Patterns

Abstract classes are often foundational in design patterns, particularly in cases like the Template Method, Factory Method, and Adapter Pattern.

Template Method Pattern

Defines the skeleton of an algorithm in an abstract class, allowing subclasses to override certain steps without altering the algorithm's structure.

public abstract class DataParser {
    // Template method defining the algorithm structure
    public final void parseData() {
        readData();
        processData();
        saveData();
    }
    protected abstract void readData();   // Steps to be customized
    protected abstract void processData();
    protected void saveData() {
        System.out.println("Data saved.");
    }
}

public class CSVDataParser extends DataParser {
    @Override
    protected void readData() { System.out.println("Reading CSV data."); }
    @Override
    protected void processData() { System.out.println("Processing CSV data."); }
}

public class JSONDataParser extends DataParser {
    @Override
    protected void readData() { System.out.println("Reading JSON data."); }
    @Override
    protected void processData() { System.out.println("Processing JSON data."); }
}

Factory Method Pattern

In the Factory Method Pattern, an abstract class defines a method for creating an object, but allows subclasses to alter the type of object that will be created. This pattern is particularly useful for scenarios where the creation process of an object requires customization by subclasses.

Let’s consider a scenario where we have different types of Document objects: WordDocument and PDFDocument. Each document type has its own way of preparing content.

// Abstract Creator class with Factory Method
public abstract class DocumentCreator {
    // Factory method to be implemented by subclasses
    protected abstract Document createDocument();

    // Template method that uses the factory method
    public void openDocument() {
        Document doc = createDocument();
        doc.prepareContent();
        System.out.println("Document opened: " + doc.getType());
    }
}

// Abstract Document class that represents the product
public abstract class Document {
    protected abstract void prepareContent();   // Step to be customized
    protected abstract String getType();
}

// Concrete Creator for Word documents
public class WordDocumentCreator extends DocumentCreator {
    @Override
    protected Document createDocument() {
        return new WordDocument();
    }
}

// Concrete Creator for PDF documents
public class PDFDocumentCreator extends DocumentCreator {
    @Override
    protected Document createDocument() {
        return new PDFDocument();
    }
}

// Concrete Product: WordDocument
public class WordDocument extends Document {
    @Override
    protected void prepareContent() {
        System.out.println("Preparing Word document content.");
    }

    @Override
    protected String getType() {
        return "Word Document";
    }
}

// Concrete Product: PDFDocument
public class PDFDocument extends Document {
    @Override
    protected void prepareContent() {
        System.out.println("Preparing PDF document content.");
    }

    @Override
    protected String getType() {
        return "PDF Document";
    }
}

public class Main {
    public static void main(String[] args) {
        DocumentCreator wordCreator = new WordDocumentCreator();
        wordCreator.openDocument();
        // Output: Preparing Word document content.
        // Document opened: Word Document

        DocumentCreator pdfCreator = new PDFDocumentCreator();
        pdfCreator.openDocument();
        // Output: Preparing PDF document content.
        // Document opened: PDF Document
    }
}

Adapter Pattern

In the Adapter Pattern, an abstract class or interface defines a target interface that different adapters can implement to wrap incompatible classes. This pattern is often used when integrating with third-party libraries or legacy systems that have incompatible interfaces.

Consider a scenario where we have an existing Rectangle class in a legacy system, but we want to use it in a new system that expects Shape objects.

// Target Interface
public abstract class Shape {
    public abstract void draw();
}

// Legacy Rectangle class (incompatible with Shape interface)
class Rectangle {
    public void drawRectangle() {
        System.out.println("Drawing a rectangle.");
    }
}

// Adapter class for Rectangle, adapting it to the Shape interface
public class RectangleAdapter extends Shape {
    private final Rectangle rectangle;

    public RectangleAdapter(Rectangle rectangle) {
        this.rectangle = rectangle;
    }

    @Override
    public void draw() {
        rectangle.drawRectangle();  // Adapter delegates to Rectangle's method
    }
}

// Legacy Circle class (incompatible with Shape interface)
class Circle {
    public void drawCircle() {
        System.out.println("Drawing a circle.");
    }
}

// Adapter class for Circle, adapting it to the Shape interface
public class CircleAdapter extends Shape {
    private final Circle circle;

    public CircleAdapter(Circle circle) {
        this.circle = circle;
    }

    @Override
    public void draw() {
        circle.drawCircle();  // Adapter delegates to Circle's method
    }
}

public class Main {
    public static void main(String[] args) {
        // Adapting a Rectangle object to the Shape interface
        Shape rectangleShape = new RectangleAdapter(new Rectangle());
        rectangleShape.draw();  // Output: Drawing a rectangle.

        // Adapting a Circle object to the Shape interface
        Shape circleShape = new CircleAdapter(new Circle());
        circleShape.draw();     // Output: Drawing a circle.
    }
}

Abstract Class with multiple inheritance

Abstract classes in Java do not support multiple inheritance. In Java, a class (whether abstract or concrete) can extend only one superclass, which is a constraint to avoid complexities that can arise from multiple inheritance, such as the Diamond Problem.

The Diamond Problem

The Diamond Problem is a classic issue in languages that support multiple inheritance (such as C++). This problem occurs when two parent classes inherit from a common superclass, and a subclass then inherits from both of these parents. The ambiguity arises because the subclass has two paths to the superclass, which could lead to conflicts in inherited behavior or state.

For example:

  • Imagine ClassA and ClassB each inherit from a common superclass, ClassC.

  • If ClassD then extends both ClassA and ClassB, there’s a risk of ambiguity as to which version of ClassC's methods or fields ClassD should inherit.

To avoid this complexity, Java allows each class (abstract or concrete) to extend only a single class

PreviousAbstractionNextInterface

Last updated 3 months ago

Was this helpful?