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
  • What is an Interface?
  • Purpose of Interfaces
  • Abstract Methods
  • Default Methods
  • Static Methods
  • Constants
  • Private Methods
  • Access Modifiers
  • Interface Inheritance
  • Nested Interface
  • Types of Nested Interfaces
  • Interface in Design Patterns
  • Strategy Pattern
  • Observer Pattern
  • Decorator Pattern
  • How does the JVM handle interfaces internally, and how does it resolve method calls for default and static methods?

Was this helpful?

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

Interface

What is an Interface?

Java interfaces are one of the core concepts of Java programming, providing a mechanism for defining a contract that classes must adhere to. A Java Interface is a reference type in Java, similar to a class, but it is a collection of abstract methods (methods without implementations) and constants. An interface provides a way to define a contract that classes can implement, meaning that any class that implements an interface must provide concrete implementations for the methods defined in the interface.

  • Reference Type: In Java, both classes and interfaces are reference types. This means that they do not hold data directly (like primitive types do), but rather reference or point to objects in memory. When we declare a variable of a class or interface type, it can reference an object of that type.

    MyClass obj = new MyClass(); // obj is a reference of type MyClass
    MyInterface obj2 = new MyClass(); // obj2 is a reference of type MyInterface
  • Key Differences:

    • Classes define both the behavior (methods) and the structure (fields) of objects.

    • Interfaces define only method signatures (and constants), without any implementation. A class that implements an interface must provide the actual implementation for the abstract methods declared in the interface.

    While an interface can define constants and abstract methods, it cannot define instance fields (variables that hold data). Additionally, interfaces can have default methods with implementations, starting from Java 8, and static methods. However, they still serve to provide a contract for what behaviors a class should implement, rather than dictating how those behaviors are implemented.

public interface InterfaceName {
    // abstract method
    void someMethod();

    // default method
    default void defaultMethod() {
        System.out.println("Default implementation");
    }

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

Purpose of Interfaces

The primary purpose of interfaces is to define a contract that classes can implement. A class that implements an interface must provide concrete implementations for all the abstract methods declared in the interface (unless the class is abstract).

Interfaces enable:

  • Abstraction: By separating the definition of a method from its implementation, interfaces allow different implementations of the same functionality.

  • Multiple Inheritance: While Java doesn't allow multiple inheritance with classes, a class can implement multiple interfaces. This allows a class to inherit different behaviors from multiple sources.

  • Loose Coupling: Interfaces help in decoupling code. The client code doesn’t need to know the details of the class implementing the interface, only the interface itself.

Abstract Methods

By default, all methods declared in an interface are abstract (i.e., they do not have a body). Any class implementing the interface must provide a concrete implementation of these methods.

interface Animal {
    void sound(); // abstract method
}

class Dog implements Animal {
    @Override
    public void sound() {
        System.out.println("Bark");
    }
}

Default Methods

Introduced in Java 8, default methods allow interfaces to provide method implementations. This feature was introduced to ensure backward compatibility when new methods are added to interfaces.

How do default methods in interfaces work, and why were they introduced?

  • Mechanics of Default Methods: Default methods are regular methods with a body in an interface, marked with the default keyword. They allow interfaces to provide a standard implementation for a method, which implementing classes can either use as-is or override.

  • Purpose of Introduction: Default methods were introduced in Java 8 to ensure backward compatibility, especially in cases like the Java Collections API. Adding new methods (e.g., forEach) to interfaces without breaking existing code was made possible by default methods.

  • Avoiding Code Duplication: Default methods also help avoid code duplication by allowing common functionality across multiple classes to be defined directly within the interface.

interface Animal {
    default void sleep() {
        System.out.println("Sleeping");
    }
}

Static Methods

Interfaces can define static methods that are independent of any instance. These methods are called using the interface name.

interface Animal {
    static void showInfo() {
        System.out.println("Animal Information");
    }
}

Constants

All fields declared in an interface are implicitly public, static, and final. They are treated as constants.

interface Animal {
    int MAX_AGE = 100; // constant
}

Private Methods

Since Java 9, interfaces can have private methods. These are used to share common code between default methods.

interface Animal {
    private void printInfo() {
        System.out.println("Animal Info");
    }

    default void show() {
        printInfo();
    }
}

Access Modifiers

All methods in an interface are implicitly public and abstract (unless they are default or static). Private methods were introduced in Java 9 for use inside the interface only. Protected and default (package-private) methods are not allowed in interfaces and will cause compilation error.

interface MyInterface {

    // Implicitly public and abstract
    void abstractMethod();

    // Public method (explicitly mentioned)
    public void publicMethod();

    // Default method (Introduced in Java 8)
    default void defaultMethod() {
        System.out.println("Default Method: Allowed in interface since Java 8");
        privateMethod(); // Private methods can be called inside interface
    }

    // Static method (Introduced in Java 8)
    static void staticMethod() {
        System.out.println("Static Method: Allowed in interface since Java 8");
    }

    // Private method (Introduced in Java 9) - Used for internal logic
    private void privateMethod() {
        System.out.println("Private Method: Only callable inside interface");
    }

    // ❌ Not Allowed: Protected and Default (Package-Private) methods
    // protected void protectedMethod();  // Compilation Error
    // void packagePrivateMethod();       // Compilation Error
}

// Implementing class
class MyClass implements MyInterface {

    @Override
    public void abstractMethod() {
        System.out.println("Overriding abstractMethod");
    }

    @Override
    public void publicMethod() {
        System.out.println("Overriding publicMethod");
    }
}

public class Main {
    public static void main(String[] args) {
        MyClass obj = new MyClass();

        obj.abstractMethod();  // Works
        obj.publicMethod();    // Works
        obj.defaultMethod();   // Works

        // Static method call (only via interface name)
        MyInterface.staticMethod();

        // ❌ Private methods cannot be called outside interface
        // obj.privateMethod(); // Compilation Error

        // ❌ Protected and default (package-private) methods are not allowed
    }
}

Interface Inheritance

Interfaces can extend other interfaces. This means one interface can inherit the abstract methods of another interface. A class implementing the extended interface must implement all methods from both the parent and the child interfaces.

How would we handle method conflicts when a class implements multiple interfaces with the same method signature?

If two interfaces define the same method signature without a default implementation, there’s no conflict; the implementing class must simply provide its own implementation of the method.

interface InterfaceA {
    void printMessage();
}

interface InterfaceB {
    void printMessage();
}

class MyClass implements InterfaceA, InterfaceB {
    @Override
    public void printMessage() {
        System.out.println("MyClass implementation of printMessage");
    }
}

public class Main {
    public static void main(String[] args) {
        MyClass obj = new MyClass();
        obj.printMessage(); // Output: MyClass implementation of printMessage
    }
}

If both interfaces have a default implementation for the same method, the implementing class must override the method to resolve the conflict. This is done by explicitly calling the desired interface’s method using InterfaceName.super.methodName() syntax within the overridden method, allowing you to specify which default method to use.

interface InterfaceA {
    default void printMessage() {
        System.out.println("InterfaceA default implementation");
    }
}

interface InterfaceB {
    default void printMessage() {
        System.out.println("InterfaceB default implementation");
    }
}

class MyClass implements InterfaceA, InterfaceB {
    @Override
    public void printMessage() {
        // Resolving the conflict by calling the specific interface's default implementation
        InterfaceA.super.printMessage();
        InterfaceB.super.printMessage();
        System.out.println("MyClass custom implementation");
    }
}

public class Main {
    public static void main(String[] args) {
        MyClass obj = new MyClass();
        obj.printMessage();
        // InterfaceA default implementation
        // InterfaceB default implementation
        // MyClass custom implementation
    }
}

interface Animal {
    void sound();
}

interface Mammal extends Animal {
    void walk();
}

class Dog implements Mammal {
    @Override
    public void sound() {
        System.out.println("Bark");
    }

    @Override
    public void walk() {
        System.out.println("Walks on four legs");
    }
}

Nested Interface

A nested interface is an interface declared inside another interface or class. It is useful when we want to logically group interfaces together or restrict their scope to a particular enclosing class. They must be implemented by another class just like a normal interface.

Types of Nested Interfaces

1. Interface inside another Interface

When an interface is declared inside another interface, it is implicitly public and static. The nested interface can be accessed using OuterInterface.InnerInterface.

// Outer Interface
interface OuterInterface {

    // Abstract method in OuterInterface
    void outerMethod();

    // Nested Interface (implicitly public and static)
    interface InnerInterface {
        void innerMethod();
    }
}

// Implementing OuterInterface
class OuterClass implements OuterInterface {

    @Override
    public void outerMethod() {
        System.out.println("Implemented outerMethod from OuterInterface");
    }
}

// Implementing InnerInterface
class InnerClass implements OuterInterface.InnerInterface {

    @Override
    public void innerMethod() {
        System.out.println("Implemented innerMethod from InnerInterface");
    }
}

public class Main {
    public static void main(String[] args) {
        // Implementing OuterInterface
        OuterInterface outerObj = new OuterClass();
        outerObj.outerMethod();

        // Implementing InnerInterface
        OuterInterface.InnerInterface innerObj = new InnerClass();
        innerObj.innerMethod();
        
        /* Output:
        Implemented outerMethod from OuterInterface
        Implemented innerMethod from InnerInterface
        */
    }
}

2. Interface inside a Class

When an interface is declared inside a class, it can have any access modifier (public, private, protected, or default). It is used when the interface should only be used within that class.

  • public interface PublicInner - Can be accessed and implemented from anywhere.

  • protected interface ProtectedInner - Can be accessed and implemented within the same package or subclasses.

  • interface DefaultInner (Package-Private) - Can be accessed and implemented only within the same package.

  • private interface PrivateInner - Cannot be directly implemented outside OuterClass, so it's accessed through a method that returns an anonymous class.

// Outer class
class OuterClass {

    // Public Nested Interface
    public interface PublicInner {
        void publicMethod();
    }

    // Protected Nested Interface
    protected interface ProtectedInner {
        void protectedMethod();
    }

    // Default (Package-Private) Nested Interface
    interface DefaultInner {
        void defaultMethod();
    }

    // Private Nested Interface
    private interface PrivateInner {
        void privateMethod();
    }

    // Method to return an instance of PrivateInner using an anonymous class
    public PrivateInner getPrivateInner() {
        return new PrivateInner() {
            @Override
            public void privateMethod() {
                System.out.println("Implemented privateMethod() from PrivateInner");
            }
        };
    }
}

// Implementing the Public Nested Interface
class PublicClass implements OuterClass.PublicInner {
    @Override
    public void publicMethod() {
        System.out.println("Implemented publicMethod() from PublicInner");
    }
}

// Implementing the Protected Nested Interface
class ProtectedClass implements OuterClass.ProtectedInner {
    @Override
    public void protectedMethod() {
        System.out.println("Implemented protectedMethod() from ProtectedInner");
    }
}

// Implementing the Default (Package-Private) Nested Interface
class DefaultClass implements OuterClass.DefaultInner {
    @Override
    public void defaultMethod() {
        System.out.println("Implemented defaultMethod() from DefaultInner");
    }
}

public class Main {
    public static void main(String[] args) {
        // Public Nested Interface
        OuterClass.PublicInner publicObj = new PublicClass();
        publicObj.publicMethod();

        // Protected Nested Interface
        OuterClass.ProtectedInner protectedObj = new ProtectedClass();
        protectedObj.protectedMethod();

        // Default Nested Interface
        OuterClass.DefaultInner defaultObj = new DefaultClass();
        defaultObj.defaultMethod();

        // Accessing Private Nested Interface via OuterClass method
        OuterClass outer = new OuterClass();
        OuterClass.PrivateInner privateObj = outer.getPrivateInner();
        privateObj.privateMethod();
        
        /* Output:
        Implemented publicMethod() from PublicInner
        Implemented protectedMethod() from ProtectedInner
        Implemented defaultMethod() from DefaultInner
        Implemented privateMethod() from PrivateInner
        */
    }
}

Interface in Design Patterns

Interface are often foundational in design patterns, particularly in cases like the Strategy Pattern, Observer Pattern, and Decorator Pattern.

Strategy Pattern

The Strategy Pattern defines a family of algorithms, encapsulates each one, and makes them interchangeable. This pattern lets the algorithm vary independently from clients that use it. Interfaces are often used here to define a "strategy" interface that various concrete implementations (strategies) can adhere to.

Example:

Imagine a context where we have different payment methods (e.g., CreditCardPayment and PayPalPayment) that follow the same PaymentStrategy interface.

// Strategy interface
public interface PaymentStrategy {
    void pay(double amount);
}

// Concrete Strategy 1
public class CreditCardPayment implements PaymentStrategy {
    private String cardNumber;

    public CreditCardPayment(String cardNumber) {
        this.cardNumber = cardNumber;
    }

    @Override
    public void pay(double amount) {
        System.out.println("Paid " + amount + " using Credit Card.");
    }
}

// Concrete Strategy 2
public class PayPalPayment implements PaymentStrategy {
    private String email;

    public PayPalPayment(String email) {
        this.email = email;
    }

    @Override
    public void pay(double amount) {
        System.out.println("Paid " + amount + " using PayPal.");
    }
}

// Context class
public class ShoppingCart {
    private PaymentStrategy paymentStrategy;

    // Set the payment strategy at runtime
    public void setPaymentStrategy(PaymentStrategy paymentStrategy) {
        this.paymentStrategy = paymentStrategy;
    }

    public void checkout(double amount) {
        paymentStrategy.pay(amount);
    }
}

public class Main {
    public static void main(String[] args) {
        ShoppingCart cart = new ShoppingCart();

        // Using credit card payment
        cart.setPaymentStrategy(new CreditCardPayment("1234-5678-9012-3456"));
        cart.checkout(150.0);  // Output: Paid 150.0 using Credit Card.

        // Switching to PayPal payment
        cart.setPaymentStrategy(new PayPalPayment("user@example.com"));
        cart.checkout(150.0);  // Output: Paid 150.0 using PayPal.
    }
}

Observer Pattern

The Observer Pattern defines a one-to-many dependency between objects, so when one object changes state, all its dependents are notified and updated automatically. Interfaces allow defining the Observer interface that can be implemented by different types of observers.

Example:

Consider a WeatherStation that notifies various Observer objects (like a MobileDevice and WebApp) whenever weather data changes.

// Observer interface
public interface Observer {
    void update(double temperature, double humidity);
}

// Concrete Observer 1
public class MobileDevice implements Observer {
    @Override
    public void update(double temperature, double humidity) {
        System.out.println("Mobile Device - Temperature: " + temperature + ", Humidity: " + humidity);
    }
}

// Concrete Observer 2
public class WebApp implements Observer {
    @Override
    public void update(double temperature, double humidity) {
        System.out.println("Web App - Temperature: " + temperature + ", Humidity: " + humidity);
    }
}

// Subject class
public class WeatherStation {
    private List<Observer> observers = new ArrayList<>();
    private double temperature;
    private double humidity;

    public void addObserver(Observer observer) {
        observers.add(observer);
    }

    public void removeObserver(Observer observer) {
        observers.remove(observer);
    }

    public void setMeasurements(double temperature, double humidity) {
        this.temperature = temperature;
        this.humidity = humidity;
        notifyObservers();
    }

    private void notifyObservers() {
        for (Observer observer : observers) {
            observer.update(temperature, humidity);
        }
    }
}

public class Main {
    public static void main(String[] args) {
        WeatherStation station = new WeatherStation();

        Observer mobileDevice = new MobileDevice();
        Observer webApp = new WebApp();

        station.addObserver(mobileDevice);
        station.addObserver(webApp);

        station.setMeasurements(28.5, 65.0);
        // Output:
        // Mobile Device - Temperature: 28.5, Humidity: 65.0
        // Web App - Temperature: 28.5, Humidity: 65.0
    }
}

Decorator Pattern

The Decorator Pattern allows behavior to be added to individual objects, dynamically, without affecting the behavior of other objects from the same class. The Component interface allows for interchangeable decorations.

Example:

Consider a scenario where we have a Coffee interface, and different coffee types can have additional options like Milk or Sugar.

// Component interface
public interface Coffee {
    String getDescription();
    double getCost();
}

// Concrete Component
public class SimpleCoffee implements Coffee {
    @Override
    public String getDescription() {
        return "Simple coffee";
    }

    @Override
    public double getCost() {
        return 5.0;
    }
}

// Abstract Decorator class implementing the same interface
public abstract class CoffeeDecorator implements Coffee {
    protected Coffee decoratedCoffee;

    public CoffeeDecorator(Coffee coffee) {
        this.decoratedCoffee = coffee;
    }

    @Override
    public String getDescription() {
        return decoratedCoffee.getDescription();
    }

    @Override
    public double getCost() {
        return decoratedCoffee.getCost();
    }
}

// Concrete Decorators
public class MilkDecorator extends CoffeeDecorator {
    public MilkDecorator(Coffee coffee) {
        super(coffee);
    }

    @Override
    public String getDescription() {
        return decoratedCoffee.getDescription() + ", Milk";
    }

    @Override
    public double getCost() {
        return decoratedCoffee.getCost() + 1.5;
    }
}

public class SugarDecorator extends CoffeeDecorator {
    public SugarDecorator(Coffee coffee) {
        super(coffee);
    }

    @Override
    public String getDescription() {
        return decoratedCoffee.getDescription() + ", Sugar";
    }

    @Override
    public double getCost() {
        return decoratedCoffee.getCost() + 0.5;
    }
}

public class Main {
    public static void main(String[] args) {
        // Simple coffee
        Coffee coffee = new SimpleCoffee();
        System.out.println(coffee.getDescription() + " $" + coffee.getCost());
        // Output: Simple coffee $5.0

        // Coffee with milk
        coffee = new MilkDecorator(coffee);
        System.out.println(coffee.getDescription() + " $" + coffee.getCost());
        // Output: Simple coffee, Milk $6.5

        // Coffee with milk and sugar
        coffee = new SugarDecorator(coffee);
        System.out.println(coffee.getDescription() + " $" + coffee.getCost());
        // Output: Simple coffee, Milk, Sugar $7.0
    }
}

How does the JVM handle interfaces internally, and how does it resolve method calls for default and static methods?

  • Interface Table (ITable): When a class implements an interface, the JVM creates an interface table (ITable) that links methods declared in the interface to the actual implementation in the class. This enables polymorphic behavior.

  • Default Method Resolution: When a default method is invoked, the JVM first checks if the class overrides the method. If not, it checks the ITable to resolve the default method in the interface. If multiple interfaces contain conflicting default methods, the JVM throws an error unless the implementing class resolves the conflict by overriding the method.

  • Static Methods: Static methods in interfaces are resolved based on the interface name, as they belong to the interface itself and cannot be called on instances of implementing classes. The JVM doesn’t look for static methods in the ITable; it simply invokes them directly on the interface.

PreviousAbstract Class & MethodNextFunctional Interfaces

Last updated 3 months ago

Was this helpful?