JAVA BASICS IN DETAIL

Java method overriding

Method overriding ( method overriding) occurs when a subclass supplies its own implementation of a method inherited from its parent. The method's purpose remains, but the specific object's behavior can differ.

A first overridden method example

class Pranesimas {
    void siusti() {
        System.out.println("Siunčiamas bendras pranešimas");
    }
}

class ElPastas extends Pranesimas {
    @Override
    void siusti() {
        System.out.println("Siunčiamas el. laiškas");
    }
}

ElPastas laiskas = new ElPastas();
laiskas.siusti();
Console output

Siunčiamas el. laiškas

  1. Pranesimas defines the general method siusti().
  2. ElPastas extends Pranesimas means that ElPastas inherits this method.
  3. The subclass uses the same method signature and supplies a more specific action.
  4. Since the object is an instance of ElPastas, its overridden method runs.

Why should you write @Override?

The annotation @Override clearly tells the compiler: “I intend to override an inherited method”. It is more than decoration: the compiler verifies that a matching method exists in the parent class.

Practical benefit

If you accidentally write siust() instead of siusti() or change the parameters, you get a compilation error rather than silently creating a different method.

Java looks at the actual object

class Pranesimas {
    void siusti() {
        System.out.println("Bendras pranešimas");
    }
}

class ElPastas extends Pranesimas {
    @Override
    void siusti() {
        System.out.println("El. laiškas");
    }
}

class Sms extends Pranesimas {
    @Override
    void siusti() {
        System.out.println("SMS žinutė");
    }
}

Pranesimas pirmas = new ElPastas();
Pranesimas antras = new Sms();

pirmas.siusti();
antras.siusti();
Console output

El. laiškas
SMS žinutė

  1. Both variables use the common type Pranesimas.
  2. The first variable actually refers to a ElPastas object, and the second to a Sms.
  3. At runtime, Java chooses the method based on the actual object type.
  4. This is called dynamic method dispatch or runtime polymorphism.

The overridden method's signature must match

class Dokumentas {
    void atidaryti() {
        System.out.println("Dokumentas atidarytas");
    }
}

class TekstinisDokumentas extends Dokumentas {
    @Override
    void atidaryti(String programa) { // Error
        System.out.println("Atidaryta su " + programa);
    }
}
Result

The code does not compile because of @Override: the parent class has no method atidaryti(String).

To override a method, its name and parameter list must match. Changing parameters creates an overload rather than an override.

Extend the parent method's behavior with super

class Kvitas {
    void spausdinti() {
        System.out.println("Parduotuvė: Miesto krautuvė");
    }
}

class PirkimoKvitas extends Kvitas {
    @Override
    void spausdinti() {
        super.spausdinti();
        System.out.println("Suma: 18.50 Eur");
    }
}

PirkimoKvitas kvitas = new PirkimoKvitas();
kvitas.spausdinti();
Console output

Parduotuvė: Miesto krautuvė
Suma: 18.50 Eur

super.spausdinti() first calls the parent class version. The subclass then adds its own information, avoiding duplication of the shared receipt header.

Access cannot be narrowed

class Paskyra {
    public void rodyti() {
        System.out.println("Paskyra");
    }
}

class DarboPaskyra extends Paskyra {
    @Override
    private void rodyti() { // Error: more restrictive access
        System.out.println("Darbo paskyra");
    }
}
Result

The code does not compile because public method is being changed in the subclass to private.

An overridden method may keep or widen access, but cannot break the promise that the parent method was publicly accessible.

Which methods cannot be overridden?

Special method cases
The methodWhat happens?
finalCannot be overridden because the parent class fixed the behavior.
privateThe subclass cannot see the method, so a matching subclass method would be new rather than an override.
staticNot overridden. A matching subclass method hides the parent's static method.
Instance methodCan be overridden if the other rules allow it.
class Saskaita {
    final void rodytiNumeri() {
        System.out.println("LT123");
    }
}

class VersloSaskaita extends Saskaita {
    // Error: a final method cannot be overridden
    void rodytiNumeri() { }
}
Result

The code does not compile because rodytiNumeri() is marked in the parent class as final.

static method hiding is not overriding

class Tevas {
    static void rodytiTipa() {
        System.out.println("Tėvo statinis metodas");
    }

    void rodytiBusena() {
        System.out.println("Tėvo egzemplioriaus metodas");
    }
}

class Vaikas extends Tevas {
    static void rodytiTipa() {
        System.out.println("Vaiko statinis metodas");
    }

    @Override
    void rodytiBusena() {
        System.out.println("Vaiko egzemplioriaus metodas");
    }
}

Tevas objektas = new Vaikas();

objektas.rodytiTipa(); // Allowed, but not recommended
Tevas.rodytiTipa();    // Recommended direct call
Vaikas.rodytiTipa();   // Calls the static method in Vaikas

objektas.rodytiBusena();
Console output

Tėvo statinis metodas
Tėvo statinis metodas
Vaiko statinis metodas
Vaiko egzemplioriaus metodas

  1. static method belongs to the class, so the clearest call uses the class name directly: Tevas.rodytiTipa() or Vaikas.rodytiTipa().
  2. Java also lets you write objektas.rodytiTipa(), even though objektas is a reference variable. This works but is misleading and discouraged.
  3. When a static method is called through a reference, Java considers the declared reference type, Tevas, rather than the actual object, and therefore runs Tevas.rodytiTipa().
  4. Vaikas.rodytiTipa() explicitly selects the static method defined in the Vaikas class.
  5. rodytiBusena() is an instance method, so Java considers the actual object, Vaikas , and runs its overridden version.
A useful rule

Call a static method through the class it belongs to. This immediately shows that it needs no specific object.

An overridden method can return a subclass type

class Dokumentas {
    Dokumentas kopijuoti() {
        return new Dokumentas();
    }
}

class Saskaita extends Dokumentas {
    @Override
    Saskaita kopijuoti() {
        return new Saskaita();
    }
}

Saskaita originalas = new Saskaita();
Saskaita kopija = originalas.kopijuoti();

System.out.println(kopija.getClass().getSimpleName());
Console output

Saskaita

The parent method returns Dokumentas, while the overridden method returns its more specific subclass, Saskaita. This is a covariant return type, which Java permits.

The checked exception rule

An overridden method cannot declare a new or broader checked (checked) exception than its parent method. It may declare the same exception, a narrower one or none. Unchecked exceptions of type RuntimeException are not subject to this restriction.

Why?

Code working with the parent type already knows which checked exceptions it must handle. A subclass cannot unexpectedly require it to handle a broader set of errors.

Overloading and overriding are different

Differences between method overloading and overriding
PropertyOverloadingOverriding
English termoverloadingoverriding
Where does it occur?Usually in the same classBetween a parent class and a subclass
ParametersMust differMust match
Selection timeAt compile timeAt runtime, based on the actual object
PurposeThe same action for different argumentsA more specific implementation of inherited behavior

More about Java method overloading

What should you remember?

  • Overriding lets a subclass change the behavior of an inherited instance method.
  • The method name and parameter list must match.
  • Always use @Overrideso the compiler can verify your intention.
  • An overridden method is selected at runtime based on the actual object type.
  • Access cannot be narrowed.
  • final, private and static methods are not overridden.
  • With super.metodas() lets you reuse and extend parent behavior.