Virtual Method in Java: How Interfaces and Polymorphism Work Together!
Updated on Jul 04, 2025 | 19 min read | 12.04K+ views
Share:
For working professionals
For fresh graduates
More
Updated on Jul 04, 2025 | 19 min read | 12.04K+ views
Share:
Table of Contents
Did you know? Java ranks 4th among the top 10 programming languages, behind Python, C++, and C, thanks to its strong support for object-oriented principles like polymorphism. |
A virtual method in Java is a non-static method that can be overridden by a subclass, enabling one of Java’s core strengths, runtime polymorphism. By default, all instance methods are virtual unless marked as final, private, or static. This allows Java to resolve method calls at runtime based on the actual object type rather than the reference type, resulting in more dynamic, flexible, and maintainable code.
In this blog, you will explore virtual function in Java in detail and their connection with inheritance and interfaces.
Ready to build powerful applications and solve complex problems? Start your journey with online software engineering courses and develop the skills needed to write efficient code and design robust software systems.
In Java, the concept of a virtual method in Java underpins dynamic method invocation and supports core principles of object-oriented design. Though Java doesn't explicitly use the term, as languages like C++ do, it fully embraces the idea through method overriding.
When a subclass provides its own version of a method defined in a superclass, Java ensures the correct method is executed based on the object's true type at runtime. This mechanism promotes modularity, reusability, and clean architecture in software development.
In 2025, programming and AI skills remain in high demand as businesses seek to innovate and improve efficiency. To enhance your expertise in Java and other technologies, consider these top courses:
Code Example: Virtual Function in Java
This example shows how a method is overridden in a subclass to provide specific behavior.
Code Snippet:
class Animal {
void sound() {
System.out.println("Animal makes a sound");
}
}
class Dog extends Animal {
@Override
void sound() {
System.out.println("Dog barks");
}
}
public class Main {
public static void main(String[] args) {
Animal animal = new Dog();
animal.sound(); // Output: Dog barks
}
}
Output:
Dog barks
Explanation:
Note:
The @Override annotation ensures that the method in the subclass is correctly overriding a method from the superclass. If the method signature in the subclass does not match any method in the superclass, the compiler will produce an error. This helps avoid mistakes, such as typos in method names or incorrect method parameters.
With a solid understanding of what is virtual function in Java, you can now explore its key features, which enable flexibility in object-oriented design.
Virtual function in Java are equipped with key features that enable dynamic behavior and enhance code reusability. This section explores these features, including how dynamic method dispatch and method overriding drive polymorphism, making Java’s object-oriented design both flexible and powerful.
Feature |
What It Means |
Example |
Why It Matters |
Dynamic Method Dispatch | Method executed depends on the actual object, not the reference type. | Animal a = new Dog(); a.sound(); → Executes Dog’s method. | Enables runtime polymorphism. |
Method Overriding | Subclass redefines a superclass method with the same signature. | Dog overrides sound() from Animal. | Adds specific behavior while keeping a common structure. |
Polymorphism | Same method call behaves differently based on object type. | a.sound() gives different results for Dog, Cat, etc. | Makes code flexible and reusable. |
Late Binding | Method is linked to its implementation at runtime. | Same as dynamic dispatch. | Supports dynamic behavior and decisions during execution. |
Code Reusability | Common logic in base class; custom behavior in subclasses. | Animal has shared logic, Dog only overrides sound(). | Reduces duplication and simplifies maintenance. |
Loose Coupling | Code interacts with superclass, not specific subclasses. | Method uses Animal type, works with Dog, Cat, etc. | Increases modularity and makes code easier to extend. |
Runtime Flexibility | Behavior changes dynamically via overridden methods. | Used in GUI events, strategy patterns, or plugin systems. | Adapts to different contexts without changing structure. |
Also Read: What is a Static Method & Static Keyword in Java?
Let’s compare Static vs Virtual Function Methods in Java and explore their key differences and use cases.
While both static and virtual functions serve important purposes in Java, they differ significantly in terms of their behavior and functionality. Static methods are bound at compile time, whereas virtual functions rely on runtime method resolution.
Below is a comparison of static and virtual method in Java:
Feature |
Static Method in Java |
Virtual Method in Java |
Binding | Compile-time (early binding) | Runtime (late binding) |
Overriding | Cannot be overridden (only hidden) | Can be overridden by subclasses |
Polymorphism | Not supported | Fully supported |
Invocation | Called using class name (e.g., ClassName.method()) | Called via object reference (e.g., obj.method()) |
Subclass Access | Accessible via class name, no object needed | Must use an object instance |
Use Case | Utility/helper methods (e.g., Math.max()) | Dynamic behavior based on object type (e.g., GUI handlers, business rules) |
Memory | Loaded once per class, shared across all instances | Resolved per object at runtime |
Performance | Slightly faster (no dynamic dispatch) | Slightly slower, but adds flexibility |
Wondering how data patterns relate to virtual method in Java? Enroll in upGrad's 6-hours Analyzing Patterns in Data and Storytelling course to help you enhance your coding expertise!
To better understand how virtual functions provide flexibility and enhance code reusability, let's explore how to implement them in Java.
Implementing virtual method in Java is all about method overriding, a key part of polymorphism. By overriding methods in subclasses, you can customize their behavior while keeping the method signature consistent.
In this section, you’ll learn how to implement virtual functions step by step, with practical examples to help you understand how it works in action.
To implement virtual function in Java, the following steps are essential:
Consider a scenario where you are designing a system to represent different types of employees. You have a generic Employee class, and subclasses for Manager and Developer.
Both subclasses override a method getSalary(), but each has a different implementation depending on their role. This is an ideal example of applying a virtual method in Java.
Code Snippet:
class Employee {
// Virtual function
double getSalary() {
return 50000;
}
}
class Manager extends Employee {
@Override
double getSalary() {
return 80000;
}
}
class Developer extends Employee {
@Override
double getSalary() {
return 60000;
}
}
public class Company {
public static void main(String[] args) {
Employee emp1 = new Manager();
Employee emp2 = new Developer();
System.out.println("Manager's Salary: " + emp1.getSalary()); // Output: 80000
System.out.println("Developer's Salary: " + emp2.getSalary()); // Output: 60000
}
}
Output:
Manager's Salary: 80000
Developer's Salary: 60000
Explanation:
Now that we've covered virtual methods in Java, let's see how interfaces enhance polymorphism, with clear roles and practical examples.
In Java, interfaces play a crucial role in enabling virtual functions by enforcing method implementation across different classes. When a method is declared in an interface, it acts as a contract that all implementing classes must fulfill, allowing dynamic method resolution at runtime. This mechanism is fundamental to achieving polymorphism, where the exact method invoked depends on the actual object type, promoting flexible and extensible designs.
The following code shows how different classes implement a common interface with a virtual function for calculating the area of geometric shapes.
Code Snippet:
// Defining the interface with a virtual function
interface Shape {
double calculateArea(); // Virtual function
}
// Implementing the interface in the Rectangle class
class Rectangle implements Shape {
double length, width;
Rectangle(double length, double width) {
this.length = length;
this.width = width;
}
@Override
public double calculateArea() {
return length * width; // Rectangle's specific implementation
}
}
// Implementing the interface in the Circle class
class Circle implements Shape {
double radius;
Circle(double radius) {
this.radius = radius;
}
@Override
public double calculateArea() {
return Math.PI * radius * radius; // Circle's specific implementation
}
}
public class Main {
public static void main(String[] args) {
Shape shape1 = new Rectangle(5, 10);
Shape shape2 = new Circle(7);
System.out.println("Rectangle Area: " + shape1.calculateArea()); // Output: 50.0
System.out.println("Circle Area: " + shape2.calculateArea()); // Output: 153.93804002589985
}
}
Output:
Rectangle Area: 50.0
Circle Area: 153.93804002589985
Explanation:
Ready to enhance your Java and OOP skills? Enroll in upGrad’s AI-Powered Full Stack Development Course by IIITB and learn advanced concepts like virtual methods and polymorphism.
Building on the concept of virtual functions with interfaces, let's explore how runtime polymorphism and method overriding further enhance flexibility in Java.
Runtime polymorphism in Java is the ability of the program to decide during execution which method to call. This feature allows Java to handle method calls dynamically, based on the actual object type at runtime.
Below are key points that clarify how runtime polymorphism is achieved and its significance when using virtual method in Java.
Key Point |
Description |
Example / Notes |
Dynamic Method Dispatch | Method calls resolved at runtime based on actual object type. | Animal a = new Dog(); a.sound(); calls Dog's sound() |
Method Overriding | Subclasses redefine superclass methods for custom behavior. | Enables flexibility without changing superclass code |
super Keyword | Access superclass method from a subclass. | Useful for extending base logic without full replacement |
Uniform Object Handling | Superclass references can point to subclass objects. | Simplifies code with polymorphic behavior |
Reduced Conditional Logic | Eliminates type checks and if-else chains. | Cleaner, more maintainable code |
Supports Extensibility | New subclasses can be added without altering existing code. | Follows the Open/Closed Principle |
Late Binding | Methods are linked to definitions at runtime, not compile time. | Enables dynamic, flexible behavior |
Code Reusability | Shared logic in superclasses or interfaces; specifics in subclasses. | Avoids duplication and promotes clean architecture |
Polymorphic Collections | Collections can hold different subclass objects and invoke overridden methods. | E.g., List<Animal> can contain Dog, Cat, etc. |
Runtime Flexibility | Program behavior adapts dynamically based on object instances. | Ideal for plugins, GUIs, and event-driven systems |
Tired of writing repetitive code? The upGrad PG Diploma in Data Science – IIIT Bangalore teaches you how Java virtual methods enable scalable OOP patterns for real-world data workflows.
Understanding runtime polymorphism through method overriding helps you How Abstract Methods Represent Pure Virtual Function in Java?
In C++, pure virtual functions use the virtual keyword without implementation, forcing subclasses to override them, making the class abstract.
Java doesn't use the virtual keywor,d but achieves the same with abstract methods inside abstract classes. These methods lack implementation and must be overridden by subclasses, ensuring specific behaviors.
Though the syntax differs, Java’s abstract methods function like C++'s pure virtual functions, supporting polymorphism and enforcing a consistent design.
Aspect |
Abstract Method (Java) |
Pure Virtual Function (C++) |
Definition | Declared without a body in an abstract class or interface | Declared with = 0 in an abstract class |
Declaration | Inside an abstract class or interface | Inside an abstract base class using virtual keyword |
Syntax | abstract void display(); | virtual void display() = 0; |
Implementation | Must be implemented by non-abstract subclasses | Must be implemented by derived classes unless also abstract |
Instantiation | Cannot instantiate abstract classes | Cannot instantiate classes with pure virtual functions |
Purpose | Defines a contract for behavior across subclasses | Enforces derived classes to implement specific behavior |
Multiple Methods | Can have many abstract methods per class | Can have many pure virtual functions per class |
Partial Implementation | Abstract classes can include both abstract and regular methods | Abstract classes can include both pure virtual and regular methods |
Interfaces | Interfaces are fully abstract (pre-Java 8), or mix default and abstract methods | Interfaces often created using classes with only pure virtual functions |
Polymorphism | Enables runtime polymorphism via method overriding | Supports runtime polymorphism via dynamic dispatch |
Curious about how cloud computing can enhance your coding skills? upGrad's Fundamentals of Cloud Computing course offers the perfect foundation, just like abstract methods lay the groundwork for pure virtual functions in Java.
After understanding abstract methods, let’s quickly compare virtual vs pure virtual functions to clarify their roles in class design.
In Java, virtual functions are implemented through method overriding, enabling runtime polymorphism where subclasses provide specific method implementations. Pure virtual functions, as in C++, do not exist explicitly in Java but are conceptually represented by abstract methods in abstract classes or interfaces.
Abstract methods must be overridden by subclasses, enforcing a contract similar to pure virtual functions and ensuring no default implementation exists. Understanding this distinction helps you design Java applications that leverage polymorphism effectively while adhering to strong abstraction principles.
Aspect |
Virtual Method (Java) |
Pure Virtual Function (C++) |
Definition | Default for all non-static methods; overriding is optional | Declared with = 0; must be overridden by subclasses |
Implementation | Can have a body in the superclass | No implementation in base class allowed |
Enforcement | Flexible—subclasses may override | Strict—subclasses must override |
Polymorphism | Enables optional dynamic behavior | Enforces consistent dynamic behavior |
Use Case | Common for shared methods with optional customization | Ideal for defining interfaces or abstract behaviors |
Java Equivalent | Abstract methods (require override) mimic pure virtual functions | Matches Java’s abstract method behavior |
In this comparison, virtual functions offer flexibility in Java, while pure virtual functions in other languages, like C++, provide a stricter level of enforcement.
Lost in messy codebases? The upGrad PG Certificate in Data Science builds your confidence to apply Java virtual methods and craft flexible, object-oriented solutions from day one.
After examining the key differences between virtual functions and pure virtual function in Java, it’s important to look at their advantages and disadvantages.
Virtual functions in Java offer great benefits, like increased flexibility, code reuse, and support for runtime polymorphism, making them essential in object-oriented programming. However, they also come with challenges, such as performance overhead and debugging difficulties.
In this section, you’ll learn the pros and cons of virtual functions, so you can make better design choices for your projects.
Here are the main advantages of virtual functions in Java:
Advantage |
Explanation |
Polymorphism | Virtual functions let methods behave differently depending on the actual object type during runtime. This makes it easy to work with different objects through a common interface. |
Dynamic Dispatch | Java decides at runtime which overridden method to call, even if the reference type is a superclass. This adds flexibility to your program. |
Code Reusability | Subclasses can reuse and modify existing methods from parent classes, reducing duplicate code and making maintenance easier. |
Extensibility | You can add new functionality by creating new subclasses without changing existing code, following good design principles. |
Interface Support | Interfaces depend on virtual functions, allowing multiple classes to implement shared behaviors in their own way, supporting modular design. |
Simplifies Code | Virtual functions reduce the need for complex conditional statements to choose which method to call, making the code cleaner. |
Supports Abstraction | Helps hide implementation details and expose only necessary behavior through method overriding. |
Improves Maintainability | Changes or improvements in subclass methods do not affect the superclass, allowing safer updates and enhancements. |
Encourages Loose Coupling | Code written against interfaces or base classes can work with new subclasses without modification, improving flexibility. |
Enables Runtime Flexibility | Behavior can be changed dynamically based on object types at runtime, useful for scenarios like event handling or plugin systems. |
While virtual functions offer significant advantages, it is also important to consider their potential drawbacks when implementing them in Java.
Disadvantage |
Explanation |
Solution |
Performance Overhead | Runtime method dispatch may slow performance in critical areas. | Use final or static methods where overriding isn’t needed. |
Increased Complexity | Deep inheritance can make code harder to read and debug. | Favor shallow hierarchies and use composition over inheritance. |
Tight Coupling | Subclasses rely heavily on base classes, reducing flexibility. | Apply the Open/Closed Principle and design with interfaces. |
Method Hiding Risks | Overlapping method names can lead to confusion or bugs. | Use @Override and follow consistent naming and overriding practices. |
Higher Memory Use | Many subclasses with overridden methods may increase memory footprint. | Avoid excessive subclassing; use delegation or shared logic where possible. |
Want to master Java's object-oriented principles and avoid the pitfalls of virtual functions? Enroll in upGrad's Java Object-Oriented Programming course today!
To make the most of virtual functions in Java while minimizing potential drawbacks, it’s essential to follow some proven best practices. Let’s explore how you can implement them effectively.
When working with virtual functions in Java, following best practices helps you write efficient, manageable, and understandable code. By adopting these principles, you can enhance the scalability of your Java applications while minimizing common challenges like code complexity and unexpected runtime behavior.
The following best practices are designed to help you optimize virtual function usage, ensuring smoother development and more reliable performance in your projects.
Using interfaces and abstract classes provides a clear structure to your code, making it easier to decouple different components. They allow for better abstraction, which is essential for managing virtual functions effectively.
To implement this, here are some key insights:
By using interfaces and abstract classes, you ensure your codebase remains flexible and extensible.
Also Read: How to Code, Compile, and Run Java Projects: A Beginner’s Guide
When overriding methods in subclasses, consistency is crucial. Ensuring that the method behavior and signature remain consistent makes the code easier to follow and maintain.
Consider these points to maintain consistency:
Consistency in method overriding provides reliability and helps maintain a predictable behavior across the codebase.
Also Read: Types of Polymorphism in Java [Static & Dynamic Polymorphism with Examples]
Instead of relying on inheritance for extending functionality, favor composition. Using composition enables you to create more flexible and maintainable systems, as it avoids deep and complex inheritance hierarchies.
Here are some tips to apply this practice effectively:
Favoring composition enhances the flexibility and maintainability of your code, reducing complexity.
Also Read: What are the Types of Inheritance in Java? Examples and Tips to Master Inheritance
While virtual functions provide powerful polymorphism capabilities, overusing them can lead to complex, hard-to-maintain code. It's essential to use them only when necessary to prevent unnecessary abstraction and complexity in your applications.
Key points to remember include:
By avoiding overuse, you ensure that your code remains simple and maintainable.
Also Read: A Complete Guide to Java Keywords
The Liskov Substitution Principle ensures that subclasses can replace their base classes without affecting the correctness of your program. This principle is vital when working with virtual functions, as it guarantees that the substitution of objects will not introduce unexpected behavior.
Consider the following strategies for adhering to LSP:
By adhering to LSP, you maintain the correctness and reliability of your code.
Also Read: Understanding the Differences Between Inheritance and Polymorphism in Java
Documenting overridden methods is essential for clarity. When you override a method, it is important to clearly explain its purpose and behavior. This will help other developers understand how your subclass changes the behavior of the parent class method.
Here’s how to document effectively:
Proper documentation ensures that your code is understandable and maintainable for other developers.
Also Read: What is Coding? A Comprehensive Guide to Software Engineers in 2025
The @Override annotation is a powerful tool that ensures the method signature in the subclass matches the method in the superclass. Using this annotation can prevent errors during the development process and provide compile-time checks.
Benefits of using the @Override annotation include:
The @Override annotation enhances code quality and prevents common errors during development.
Also Read: Types of Variables in Java: Java Variables Explained
To reduce unnecessary exposure of virtual functions, it is recommended to limit their visibility. Restricting access to methods when they are not needed outside the class or package ensures better encapsulation and protects the integrity of your code.
Key points to follow include:
Minimizing method visibility enhances security and helps maintain the integrity of your codebase.
Also Read: Difference Between Overloading and Overriding in Java: Understanding the Key Concepts in 2025
Changing the method signature in a subclass, including the return type or parameters, can break existing code dependencies. Here are the best practices to avoid signature changes.
Maintaining method signature consistency preserves code compatibility and prevents errors.
A virtual method in Java is any non-static method that a subclass can override. These methods support runtime polymorphism, where the JVM determines the method to execute based on the actual object type, not the reference type. This allows dynamic method dispatch, making Java programs more flexible, extensible, and aligned with object-oriented design principles.
If you're looking to strengthen your Java skills, upGrad offers practical, mentor-led programs that bridge theory with hands-on experience. These programs are ideal for building confidence in key concepts like polymorphism, inheritance, and interface-based design.
Here are some of the top courses available to help you grow.
Feeling unsure about where to begin with your programming career? Connect with upGrad’s expert counselors or visit your nearest upGrad offline centre to explore a learning plan tailored to your goals. Transform your programming journey today with upGrad!
Boost your career with our popular Software Engineering courses, offering hands-on training and expert guidance to turn you into a skilled software developer.
Master in-demand Software Development skills like coding, system design, DevOps, and agile methodologies to excel in today’s competitive tech industry.
Stay informed with our widely-read Software Development articles, covering everything from coding techniques to the latest advancements in software engineering.
References:
https://6sense.com/tech/languages/java-market-share
https://www.tiobe.com/tiobe-index/
900 articles published
Director of Engineering @ upGrad. Motivated to leverage technology to solve problems. Seasoned leader for startups and fast moving orgs. Working on solving problems of scale and long term technology s...
Get Free Consultation
By submitting, I accept the T&C and
Privacy Policy
India’s #1 Tech University
Executive PG Certification in AI-Powered Full Stack Development
77%
seats filled
Top Resources