Method Overloading vs Overriding
Introduction
Polymorphism — Compile-Time vs Runtime showed two ways one method name can run different code. With overloading, a class has several methods with the same name and different parameters. With overriding, a child class writes its own version of a method it inherits. The two are easy to mix up, because both reuse a name. They follow different rules, though, and they are chosen at different moments: an overload when the code compiles, an override while the program runs.
Below they stand side by side, with every rule tested on real code, followed by the cases that catch people out: a class that does both, a change of return type, static methods, and an overload chosen by the type a variable was declared with.
The Core Difference
Both reuse a method's name. Almost everything else about them differs:
| Aspect | Overloading | Overriding |
|---|---|---|
| What changes | The parameter list | The body |
| Where | In one class, or added in a child | A parent and its child |
| Chosen | At compile time, from the arguments' types | At run time, from the object |
| Signature | Must differ | Must match the parent's |
| Return type | Plays no part | The same, or in Java a subtype |
| Java, C++ and C# | Yes | Yes |
| Python | No: default values, or a second name | Yes |
| TypeScript | Signatures over one body | Yes |
| Go | No: a name for each version | No inheritance: embedding instead |
A short way to hold it: overloading keeps the name and changes the parameters, while overriding keeps the name and the parameters and changes the body, in a child class. The picture shows one example of each from the listings below, and a class that does both.

Method Overloading: Same Name, Different Parameters
Overloading means writing several methods with the same name and different parameter lists. The Java tutorial explains how the compiler tells them apart: "Overloaded methods are differentiated by the number and the type of the arguments passed into the method." For every call, the compiler looks at the arguments and picks the one version that takes them, before the program ever runs.
In Java the rules are these:
- The name stays the same.
- The parameter lists differ: in how many parameters there are, in their types, or in their order.
- The return type does not count. In the Java tutorial's words: "The compiler does not consider return type when differentiating methods, so you cannot declare two methods with the same signature even if they have a different return type."
- The versions may have different access and throw different exceptions, since neither is part of the choice. A test gave one version
publicaccess and anotherprivateaccess with athrowsclause, and javac compiled them.
Here is a logger with four versions of log. Java, C++ and C# write four methods with one name. Python, TypeScript and Go have no overloading of this kind, so each says in a comment how it gets the same effect: Python gives one method default values and a separate name for the error-code version, TypeScript writes overload signatures over one body, and Go gives each version a name of its own.
# Python has no overloading: one method with default values covers the first three
# versions, and the error-code version gets a name of its own
class Logger:
def log(self, message: str, level: str = "INFO",
context: str | None = None) -> None:
if context is None:
print(f"[{level.upper()}] {message}")
else:
print(f"[{level.upper()}] [{context}] {message}")
def log_error(self, error_code: int, message: str) -> None:
print(f"[ERROR-{error_code}] {message}")
logger = Logger()
logger.log("Server started")
logger.log("Memory usage high", level="WARN")
logger.log("Connection failed", level="ERROR", context="Database")
logger.log_error(500, "Internal Server Error")import java.util.Locale;
// The same name with four parameter lists: method overloading
public class Logger {
// A message on its own
public void log(String message) {
System.out.println("[INFO] " + message);
}
// A message with a level
public void log(String level, String message) {
System.out.println("[" + level.toUpperCase(Locale.ROOT) + "] " + message);
}
// A message with a level and the place it came from
public void log(String level, String message, String context) {
String upper = level.toUpperCase(Locale.ROOT);
System.out.println("[" + upper + "] [" + context + "] " + message);
}
// A message with an error code
public void log(int errorCode, String message) {
System.out.println("[ERROR-" + errorCode + "] " + message);
}
// A version that differed from the first only in its return type would not compile:
// public int log(String message) { ... }
public static void main(String[] args) {
Logger logger = new Logger();
// The compiler picks each version from the arguments
logger.log("Server started");
logger.log("WARN", "Memory usage high");
logger.log("ERROR", "Connection failed", "Database");
logger.log(500, "Internal Server Error");
}
}#include <cctype>
#include <cstdio>
#include <string>
std::string upper(std::string s) {
for (char& ch : s) {
ch = static_cast<char>(std::toupper(static_cast<unsigned char>(ch)));
}
return s;
}
// The same name with four parameter lists: method overloading
class Logger {
public:
// A message on its own
void log(const std::string& message) const {
std::printf("[INFO] %s\n", message.c_str());
}
// A message with a level
void log(const std::string& level, const std::string& message) const {
std::printf("[%s] %s\n", upper(level).c_str(), message.c_str());
}
// A message with a level and the place it came from
void log(const std::string& level, const std::string& message,
const std::string& context) const {
std::printf("[%s] [%s] %s\n", upper(level).c_str(), context.c_str(),
message.c_str());
}
// A message with an error code
void log(int errorCode, const std::string& message) const {
std::printf("[ERROR-%d] %s\n", errorCode, message.c_str());
}
// A version that differed from the first only in its return type would not compile:
// int log(const std::string& message) const;
};
int main() {
Logger logger;
// The compiler picks each version from the arguments
logger.log("Server started");
logger.log("WARN", "Memory usage high");
logger.log("ERROR", "Connection failed", "Database");
logger.log(500, "Internal Server Error");
return 0;
}// TypeScript has overload signatures over one body: the body tells the versions
// apart by the arguments it is given, when the program runs
class Logger {
log(message: string): void;
log(level: string, message: string): void;
log(level: string, message: string, context: string): void;
log(errorCode: number, message: string): void;
log(first: string | number, message?: string, context?: string): void {
if (typeof first === "number") {
console.log(`[ERROR-${first}] ${message}`);
} else if (message === undefined) {
console.log(`[INFO] ${first}`);
} else if (context === undefined) {
console.log(`[${first.toUpperCase()}] ${message}`);
} else {
console.log(`[${first.toUpperCase()}] [${context}] ${message}`);
}
}
}
const logger = new Logger();
logger.log("Server started");
logger.log("WARN", "Memory usage high");
logger.log("ERROR", "Connection failed", "Database");
logger.log(500, "Internal Server Error");using System;
// The same name with four parameter lists: method overloading
public class Logger
{
// A message on its own
public void Log(string message)
{
Console.WriteLine($"[INFO] {message}");
}
// A message with a level
public void Log(string level, string message)
{
Console.WriteLine($"[{level.ToUpperInvariant()}] {message}");
}
// A message with a level and the place it came from
public void Log(string level, string message, string context)
{
Console.WriteLine($"[{level.ToUpperInvariant()}] [{context}] {message}");
}
// A message with an error code
public void Log(int errorCode, string message)
{
Console.WriteLine($"[ERROR-{errorCode}] {message}");
}
// A version that differed from the first only in its return type would not compile:
// public int Log(string message) { ... }
public static void Main()
{
var logger = new Logger();
// The compiler picks each version from the arguments
logger.Log("Server started");
logger.Log("WARN", "Memory usage high");
logger.Log("ERROR", "Connection failed", "Database");
logger.Log(500, "Internal Server Error");
}
}package main
import (
"fmt"
"strings"
)
// Go has no overloading: each version gets a name of its own
type Logger struct{}
// Log writes a message on its own
func (Logger) Log(message string) {
fmt.Printf("[INFO] %s\n", message)
}
// LogLevel writes a message with a level
func (Logger) LogLevel(level, message string) {
fmt.Printf("[%s] %s\n", strings.ToUpper(level), message)
}
// LogContext writes a message with a level and the place it came from
func (Logger) LogContext(level, message, context string) {
fmt.Printf("[%s] [%s] %s\n", strings.ToUpper(level), context, message)
}
// LogError writes a message with an error code
func (Logger) LogError(errorCode int, message string) {
fmt.Printf("[ERROR-%d] %s\n", errorCode, message)
}
func main() {
logger := Logger{}
logger.Log("Server started")
logger.LogLevel("WARN", "Memory usage high")
logger.LogContext("ERROR", "Connection failed", "Database")
logger.LogError(500, "Internal Server Error")
}It prints:
[INFO] Server started
[WARN] Memory usage high
[ERROR] [Database] Connection failed
[ERROR-500] Internal Server Error
Each call went to the version whose parameters fit its arguments: one string, two strings, three strings, or a number and a string.
Python has one more tool, the @overload decorator from the typing module, which has been part of Python since version 3.5. It does not create versions that run. The typing documentation says the decorated signatures "are for the benefit of the type checker only", and the one plain definition after them is the one that runs.
Method Overriding: Same Signature, a Child Class
Overriding means that a child class writes its own version of a method it inherits, with the same name and the same parameters. The Java tutorial defines it: "An instance method in a subclass with the same signature (name, plus the number and the type of its parameters) and return type as an instance method in the superclass overrides the superclass's method." Which version runs is decided while the program runs, by the object the method is called on.
In Java the rules are these:
- The name and the parameter list are the same as the parent's.
- The return type is the same, or a subtype of it. The Java tutorial: "An overriding method can also return a subtype of the type returned by the overridden method." Such a return type is called a covariant return type.
- The child may widen the method's access and may not narrow it. The Java tutorial: "The access specifier for an overriding method can allow more, but not less, access than the overridden method." A test that made a
publicmethodprivatein the child stopped javac withattempting to assign weaker access privileges; was public. - A method marked
finalcannot be overridden. The Java tutorial: "You use the final keyword in a method declaration to indicate that the method cannot be overridden by subclasses." javac reportedoverridden method is finalwhen a child tried. - A static method is not overridden. In the Java tutorial's words: "If a subclass defines a static method with the same signature as a static method in the superclass, then the method in the subclass hides the one in the superclass." The tricky cases below show what that means.
- Write
@Overrideon every method you mean to override, so that javac checks that it really overrides one.
Here is a checkout. PaymentProcessor has a default way to take a payment, and two children override its methods. The fees are this example's own; real payment services publish their own prices.
class PaymentProcessor:
"""The parent class: the default way to take a payment. The fees are this
example's own."""
def process(self, amount: float) -> bool:
print(f"Processing ${amount:.2f} by default")
return True
# The default fee: 3%
def get_fee(self, amount: float) -> float:
return amount * 0.03
# Calls get_fee() on this object, so a child's own fee is the one used
def receipt(self, amount: float) -> str:
fee = self.get_fee(amount)
return f"Amount: ${amount:.2f}, Fee: ${fee:.2f}, Total: ${amount + fee:.2f}"
class CardProcessor(PaymentProcessor):
"""Overrides two methods."""
def process(self, amount: float) -> bool:
print(f"Card: charging ${amount:.2f}")
return True
# A card's fee: 2.9% plus 0.30
def get_fee(self, amount: float) -> float:
return amount * 0.029 + 0.30
class WalletProcessor(PaymentProcessor):
"""Overrides two methods and extends a third."""
def __init__(self, account: str) -> None:
self.account = account
def process(self, amount: float) -> bool:
print(f"Wallet: charging ${amount:.2f}")
return True
# A wallet's fee: 3.49% plus 0.49
def get_fee(self, amount: float) -> float:
return amount * 0.0349 + 0.49
# Extended: the parent's receipt first, then the account it was paid from
def receipt(self, amount: float) -> str:
return super().receipt(amount) + f"\nWallet account: {self.account}"
# Works with any processor: each object runs its own versions
def checkout(processor: PaymentProcessor, amount: float) -> None:
processor.process(amount)
print(processor.receipt(amount))
print()
checkout(CardProcessor(), 100.0)
checkout(WalletProcessor("alice@example.com"), 100.0)import java.util.Locale;
// The parent class: the default way to take a payment (the fees are this example's own)
class PaymentProcessor {
public boolean process(double amount) {
System.out.printf(Locale.ROOT, "Processing $%.2f by default%n", amount);
return true;
}
// The default fee: 3%
public double getFee(double amount) {
return amount * 0.03;
}
// Calls getFee() on this object, so a child's own fee is the one used
public String receipt(double amount) {
double fee = getFee(amount);
return String.format(Locale.ROOT, "Amount: $%.2f, Fee: $%.2f, Total: $%.2f",
amount, fee, amount + fee);
}
}
// Overrides two methods
class CardProcessor extends PaymentProcessor {
@Override
public boolean process(double amount) {
System.out.printf(Locale.ROOT, "Card: charging $%.2f%n", amount);
return true;
}
// A card's fee: 2.9% plus 0.30
@Override
public double getFee(double amount) {
return amount * 0.029 + 0.30;
}
}
// Overrides two methods and extends a third
class WalletProcessor extends PaymentProcessor {
private final String account;
WalletProcessor(String account) {
this.account = account;
}
@Override
public boolean process(double amount) {
System.out.printf(Locale.ROOT, "Wallet: charging $%.2f%n", amount);
return true;
}
// A wallet's fee: 3.49% plus 0.49
@Override
public double getFee(double amount) {
return amount * 0.0349 + 0.49;
}
// Extended: the parent's receipt first, then the account it was paid from
@Override
public String receipt(double amount) {
return super.receipt(amount) + "\nWallet account: " + account;
}
}
public class CheckoutDemo {
// Works with any processor: each object runs its own versions
static void checkout(PaymentProcessor processor, double amount) {
processor.process(amount);
System.out.println(processor.receipt(amount));
System.out.println();
}
public static void main(String[] args) {
checkout(new CardProcessor(), 100.0);
checkout(new WalletProcessor("alice@example.com"), 100.0);
}
}#include <cstdio>
#include <string>
#include <utility>
// The parent class: the default way to take a payment (the fees are this example's own)
class PaymentProcessor {
public:
virtual ~PaymentProcessor() = default;
virtual bool process(double amount) const {
std::printf("Processing $%.2f by default\n", amount);
return true;
}
// The default fee: 3%
virtual double getFee(double amount) const { return amount * 0.03; }
// Calls getFee() on this object, so a child's own fee is the one used
virtual std::string receipt(double amount) const {
double fee = getFee(amount);
char text[96];
std::snprintf(text, sizeof text, "Amount: $%.2f, Fee: $%.2f, Total: $%.2f",
amount, fee, amount + fee);
return text;
}
};
// Overrides two methods
class CardProcessor : public PaymentProcessor {
public:
bool process(double amount) const override {
std::printf("Card: charging $%.2f\n", amount);
return true;
}
// A card's fee: 2.9% plus 0.30
double getFee(double amount) const override { return amount * 0.029 + 0.30; }
};
// Overrides two methods and extends a third
class WalletProcessor : public PaymentProcessor {
public:
explicit WalletProcessor(std::string account) : account(std::move(account)) {}
bool process(double amount) const override {
std::printf("Wallet: charging $%.2f\n", amount);
return true;
}
// A wallet's fee: 3.49% plus 0.49
double getFee(double amount) const override { return amount * 0.0349 + 0.49; }
// Extended: the parent's receipt first, then the account it was paid from
std::string receipt(double amount) const override {
return PaymentProcessor::receipt(amount) + "\nWallet account: " + account;
}
private:
std::string account;
};
// Works with any processor: each object runs its own versions
void checkout(const PaymentProcessor& processor, double amount) {
processor.process(amount);
std::printf("%s\n\n", processor.receipt(amount).c_str());
}
int main() {
checkout(CardProcessor(), 100.0);
checkout(WalletProcessor("alice@example.com"), 100.0);
return 0;
}// The parent class: the default way to take a payment (the fees are this example's own)
class PaymentProcessor {
process(amount: number): boolean {
console.log(`Processing $${amount.toFixed(2)} by default`);
return true;
}
// The default fee: 3%
getFee(amount: number): number {
return amount * 0.03;
}
// Calls getFee() on this object, so a child's own fee is the one used
receipt(amount: number): string {
const fee = this.getFee(amount);
const total = (amount + fee).toFixed(2);
return `Amount: $${amount.toFixed(2)}, Fee: $${fee.toFixed(2)}, Total: $${total}`;
}
}
// Overrides two methods
class CardProcessor extends PaymentProcessor {
override process(amount: number): boolean {
console.log(`Card: charging $${amount.toFixed(2)}`);
return true;
}
// A card's fee: 2.9% plus 0.30
override getFee(amount: number): number {
return amount * 0.029 + 0.3;
}
}
// Overrides two methods and extends a third
class WalletProcessor extends PaymentProcessor {
constructor(private readonly account: string) {
super();
}
override process(amount: number): boolean {
console.log(`Wallet: charging $${amount.toFixed(2)}`);
return true;
}
// A wallet's fee: 3.49% plus 0.49
override getFee(amount: number): number {
return amount * 0.0349 + 0.49;
}
// Extended: the parent's receipt first, then the account it was paid from
override receipt(amount: number): string {
return `${super.receipt(amount)}\nWallet account: ${this.account}`;
}
}
// Works with any processor: each object runs its own versions
function checkout(processor: PaymentProcessor, amount: number): void {
processor.process(amount);
console.log(processor.receipt(amount));
console.log();
}
checkout(new CardProcessor(), 100.0);
checkout(new WalletProcessor("alice@example.com"), 100.0);using System;
using System.Globalization;
// The parent class: the default way to take a payment (the fees are this example's own)
public class PaymentProcessor
{
protected static string Money(double x) =>
x.ToString("F2", CultureInfo.InvariantCulture);
public virtual bool Process(double amount)
{
Console.WriteLine($"Processing ${Money(amount)} by default");
return true;
}
// The default fee: 3%
public virtual double GetFee(double amount)
{
return amount * 0.03;
}
// Calls GetFee() on this object, so a child's own fee is the one used
public virtual string Receipt(double amount)
{
double fee = GetFee(amount);
string total = Money(amount + fee);
return $"Amount: ${Money(amount)}, Fee: ${Money(fee)}, Total: ${total}";
}
}
// Overrides two methods
public class CardProcessor : PaymentProcessor
{
public override bool Process(double amount)
{
Console.WriteLine($"Card: charging ${Money(amount)}");
return true;
}
// A card's fee: 2.9% plus 0.30
public override double GetFee(double amount)
{
return amount * 0.029 + 0.30;
}
}
// Overrides two methods and extends a third
public class WalletProcessor : PaymentProcessor
{
private readonly string account;
public WalletProcessor(string account)
{
this.account = account;
}
public override bool Process(double amount)
{
Console.WriteLine($"Wallet: charging ${Money(amount)}");
return true;
}
// A wallet's fee: 3.49% plus 0.49
public override double GetFee(double amount)
{
return amount * 0.0349 + 0.49;
}
// Extended: the parent's receipt first, then the account it was paid from
public override string Receipt(double amount)
{
return base.Receipt(amount) + "\nWallet account: " + account;
}
}
public static class CheckoutDemo
{
// Works with any processor: each object runs its own versions
static void Checkout(PaymentProcessor processor, double amount)
{
processor.Process(amount);
Console.WriteLine(processor.Receipt(amount));
Console.WriteLine();
}
public static void Main()
{
Checkout(new CardProcessor(), 100.0);
Checkout(new WalletProcessor("alice@example.com"), 100.0);
}
}package main
import "fmt"
// Go has no inheritance: each processor embeds a PaymentProcessor for the default
// methods, and the Processor interface lets checkout take any of them.
// (The fees are this example's own.)
type Processor interface {
Process(amount float64) bool
GetFee(amount float64) float64
Receipt(amount float64) string
}
// PaymentProcessor is the default way to take a payment
type PaymentProcessor struct{}
func (PaymentProcessor) Process(amount float64) bool {
fmt.Printf("Processing $%.2f by default\n", amount)
return true
}
// GetFee is the default fee: 3%
func (PaymentProcessor) GetFee(amount float64) float64 {
return amount * 0.03
}
func (p PaymentProcessor) Receipt(amount float64) string {
return receipt(p, amount)
}
// receipt is handed the Processor, so a processor's own fee is the one used: a method
// that comes from an embedded PaymentProcessor would call PaymentProcessor's GetFee
func receipt(p Processor, amount float64) string {
fee := p.GetFee(amount)
return fmt.Sprintf("Amount: $%.2f, Fee: $%.2f, Total: $%.2f", amount, fee, amount+fee)
}
// CardProcessor overrides two methods
type CardProcessor struct{ PaymentProcessor }
func (CardProcessor) Process(amount float64) bool {
fmt.Printf("Card: charging $%.2f\n", amount)
return true
}
// GetFee is a card's fee: 2.9% plus 0.30
func (CardProcessor) GetFee(amount float64) float64 {
return amount*0.029 + 0.30
}
func (c CardProcessor) Receipt(amount float64) string {
return receipt(c, amount)
}
// WalletProcessor overrides two methods and extends a third
type WalletProcessor struct {
PaymentProcessor
account string
}
func (WalletProcessor) Process(amount float64) bool {
fmt.Printf("Wallet: charging $%.2f\n", amount)
return true
}
// GetFee is a wallet's fee: 3.49% plus 0.49
func (WalletProcessor) GetFee(amount float64) float64 {
return amount*0.0349 + 0.49
}
// Receipt is extended: the shared receipt first, then the account it was paid from
func (w WalletProcessor) Receipt(amount float64) string {
return receipt(w, amount) + "\nWallet account: " + w.account
}
// checkout works with any processor: each value runs its own versions
func checkout(p Processor, amount float64) {
p.Process(amount)
fmt.Println(p.Receipt(amount))
fmt.Println()
}
func main() {
checkout(CardProcessor{}, 100.0)
checkout(WalletProcessor{account: "alice@example.com"}, 100.0)
}It prints:
Card: charging $100.00
Amount: $100.00, Fee: $3.20, Total: $103.20
Wallet: charging $100.00
Amount: $100.00, Fee: $3.98, Total: $103.98
Wallet account: alice@example.com
checkout knows only that it has a PaymentProcessor. For the first payment the card processor's own process and getFee ran, and for the second the wallet processor's. WalletProcessor also extends receipt: it calls the parent's version through super and adds the account the payment came from. And receipt calls getFee() on the same object, so each child's own fee reached its receipt: 3.20 for the card and 3.98 for the wallet.
Many of the patterns in Design Patterns - Low Level Design rest on overriding. In Template Method Pattern — Algorithm Skeleton, for one, a parent class fixes the order of an algorithm's steps and its children override the steps themselves.
Both in One Class
A child class can override a method and overload it in the same class. Here Child overrides greet(name) and adds greet(name, times):
# A parent with one greet()
class Parent:
def greet(self, name: str) -> None:
print(f"Hello, {name}")
# A child that overrides greet(). Python has no overloading: the same method takes an
# optional times, which covers what a second version would add
class Child(Parent):
def greet(self, name: str, times: int = 1) -> None:
for _ in range(times):
print(f"Hi, {name}!")
# Declared a Parent, but the object is a Child: the child's version runs
parent: Parent = Child()
parent.greet("Ana")
child = Child()
child.greet("Ben", 2)// A parent with one greet()
class Parent {
public void greet(String name) {
System.out.println("Hello, " + name);
}
}
// A child that overrides greet() and also overloads it
class Child extends Parent {
// Overriding: the same name and the same parameters
@Override
public void greet(String name) {
System.out.println("Hi, " + name + "!");
}
// Overloading: the same name and a different parameter list
public void greet(String name, int times) {
for (int i = 0; i < times; i++) {
greet(name);
}
}
}
public class GreetDemo {
public static void main(String[] args) {
// Declared a Parent, but the object is a Child: the child's override runs
Parent parent = new Child();
parent.greet("Ana");
// Declared a Child, so the compiler can find the two-parameter version
Child child = new Child();
child.greet("Ben", 2);
}
}#include <cstdio>
#include <memory>
#include <string>
// A parent with one greet()
class Parent {
public:
virtual ~Parent() = default;
virtual void greet(const std::string& name) const {
std::printf("Hello, %s\n", name.c_str());
}
};
// A child that overrides greet() and also overloads it
class Child : public Parent {
public:
// Overriding: the same name and the same parameters
void greet(const std::string& name) const override {
std::printf("Hi, %s!\n", name.c_str());
}
// Overloading: the same name and a different parameter list
void greet(const std::string& name, int times) const {
for (int i = 0; i < times; i++) {
greet(name);
}
}
};
int main() {
// Declared a Parent, but the object is a Child: the child's override runs
std::unique_ptr<Parent> parent = std::make_unique<Child>();
parent->greet("Ana");
// Declared a Child, so the compiler can find the two-parameter version
Child child;
child.greet("Ben", 2);
return 0;
}// A parent with one greet()
class Parent {
greet(name: string): void {
console.log(`Hello, ${name}`);
}
}
// A child that overrides greet() and also overloads it. TypeScript writes the
// overload as a second signature over the same body
class Child extends Parent {
override greet(name: string): void;
override greet(name: string, times: number): void;
override greet(name: string, times = 1): void {
for (let i = 0; i < times; i++) {
console.log(`Hi, ${name}!`);
}
}
}
// Declared a Parent, but the object is a Child: the child's override runs
const parent: Parent = new Child();
parent.greet("Ana");
// Declared a Child, so the compiler can find the two-parameter version
const child = new Child();
child.greet("Ben", 2);
// Its own module, so this parent does not clash with the browser's parent
export {};using System;
// A parent with one Greet()
public class Parent
{
public virtual void Greet(string name)
{
Console.WriteLine($"Hello, {name}");
}
}
// A child that overrides Greet() and also overloads it
public class Child : Parent
{
// Overriding: the same name and the same parameters
public override void Greet(string name)
{
Console.WriteLine($"Hi, {name}!");
}
// Overloading: the same name and a different parameter list
public void Greet(string name, int times)
{
for (int i = 0; i < times; i++)
{
Greet(name);
}
}
}
public static class GreetDemo
{
public static void Main()
{
// Declared a Parent, but the object is a Child: the child's override runs
Parent parent = new Child();
parent.Greet("Ana");
// Declared a Child, so the compiler can find the two-parameter version
var child = new Child();
child.Greet("Ben", 2);
}
}package main
import "fmt"
// Go has neither inheritance nor overloading: Child embeds a Parent and writes its own
// Greet, which the Greeter interface reaches; the second version gets a name of its own
type Greeter interface {
Greet(name string)
}
// Parent has one Greet
type Parent struct{}
func (Parent) Greet(name string) {
fmt.Printf("Hello, %s\n", name)
}
// Child writes its own Greet: the same name and the same parameters
type Child struct{ Parent }
func (Child) Greet(name string) {
fmt.Printf("Hi, %s!\n", name)
}
// GreetTimes is the two-parameter version, with a name of its own
func (c Child) GreetTimes(name string, times int) {
for i := 0; i < times; i++ {
c.Greet(name)
}
}
func main() {
// A Greeter that holds a Child: the child's Greet runs
var parent Greeter = Child{}
parent.Greet("Ana")
child := Child{}
child.GreetTimes("Ben", 2)
}It prints:
Hi, Ana!
Hi, Ben!
Hi, Ben!
Look at what the listing does not do. parent holds a Child, and a Child has greet(name, times), yet the listing calls the two-parameter version only through child. Through parent the call does not compile. A test changed parent.greet("Ana") to parent.greet("Ana", 2), and javac stopped with this:
error: method greet in class Parent cannot be applied to given types;
required: String
found: String,int
reason: actual and formal argument lists differ in length
The variable is declared Parent, and Parent has no greet that takes a String and an int, so the compiler refuses the call whatever object the variable holds. C++, C# and TypeScript refused the same call, each with its own message about the number of arguments. Python ran it and printed Hi, Ana! twice: Python checks nothing before the program runs, and the object was a Child.
Watch the Two Moments
Every call to an overloaded or overridden method passes two moments. When the code compiles, the compiler looks only at the type the variable was declared with and picks one of that type's methods, or refuses the call. While the program runs, the object in the variable runs its own body for the method the compiler picked.
Here are the same Parent and Child. Choose how x is declared, the object put in it and the call, then press Compile and run. Start with Parent, new Child() and greet("Ana"). Then switch the call to greet("Ana", 2), and after that declare x as Child. You can also try to put a new Parent() into a Child variable.

Tricky Cases
Changing only the return type. Two methods that differ only in their return type do not compile, because a call such as add(3, 5) would look the same for both. A test with int add(int a, int b) and double add(int a, int b) in one class stopped javac with method add(int,int) is already defined in class Calculator.
Overriding is different here. A child's version may return a more specific type than the parent's, a covariant return type:
class Factory { Animal create() { return new Animal(); } }
class DogFactory extends Factory {
@Override Dog create() { return new Dog(); } // allowed: a Dog is an Animal
}A test called create() through a Factory variable that held a DogFactory, and got a Dog. A return type that is not a subtype is refused: return type String is not compatible with Animal.
Static methods. A static method belongs to the class, so there is no object to choose between versions. When a child declares a static method with the same signature as its parent's, the child's hides the parent's. The Java tutorial explains which one runs: "The version of the hidden static method that gets invoked depends on whether it is invoked from the superclass or the subclass."
class Parent { static String describe() { return "a parent"; } }
class Child extends Parent { static String describe() { return "a child"; } }
Parent p = new Child();
System.out.println(p.describe()); // a parent: the declared type decidesA test printed a parent for Parent.describe(), a child for Child.describe(), and a parent for p.describe(), although p holds a Child. Called through a variable, a static method follows the variable's declared type. javac warns about such a call when its warnings are on: [static] static method should be qualified by type name, Parent, instead of by an expression. It refuses @Override on a static method (static method describe() in Child cannot be annotated with @Override). And as the Java tutorial says, "You will get a compile-time error if you attempt to change an instance method in the superclass to a static method in the subclass, and vice versa." javac said overriding method is static for the one and overridden method is static for the other.
An overload chosen by the declared type. Since overloads are chosen when the code compiles, the compiler goes by the type each argument was declared with. Here text holds a string, but it is declared Object:
static void show(Object value) { System.out.println("show(Object)"); }
static void show(String value) { System.out.println("show(String)"); }
Object text = "hello";
show(text); // prints show(Object): the declared type is ObjectA test printed show(Object) for show(text) and show(String) for show("hello"). Overriding works the other way round: it follows the object.
Common Mistakes
Mistake 1: writing an overload when you meant an override.
class Child extends Parent {
// A second parameter makes this an overload, so Parent's process(String) still runs
public void process(String data, int flags) { System.out.println(data); }
}If Parent has process(String data), this is a second method beside it. A test called process("report") through a Parent variable that held a Child, and the parent's version ran: Parent: report. With @Override on the child's method, javac refused it: process(String,int) in Child does not override or implement a method from a supertype. To override, keep the parameters exactly the same: public void process(String data). The same annotation also catches a misspelled method name, as Polymorphism — Compile-Time vs Runtime shows.
Mistake 2: too many overloads. A method with many overloads is hard to read and easy to call with the wrong arguments. The Java tutorial's advice: "Overloaded methods should be used sparingly, as they can make code much less readable." When the versions are only different ways to pass optional settings, a parameter object (one class that holds the settings) or the builder from Builder Pattern reads better.
Key Takeaways
- Overloading gives one name several parameter lists. The compiler picks a version from the declared types of the arguments, and the return type plays no part.
- Overriding keeps the name and the parameters in a child class and changes the body. The object picks the version while the program runs.
- Every call passes both moments: the declared type decides which methods can be called at all, and the object decides which body runs.
- In Java, mark every override with
@Override. Static methods are hidden, andfinalmethods cannot be overridden. - Enums — Type-Safe Constants comes next: a type whose values are a fixed set of named constants.