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();Siunčiamas el. laiškas
Pranesimasdefines the general methodsiusti().ElPastas extends Pranesimasmeans thatElPastasinherits this method.- The subclass uses the same method signature and supplies a more specific action.
- 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.
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();El. laiškas
SMS žinutė
- Both variables use the common type
Pranesimas. - The first variable actually refers to a
ElPastasobject, and the second to aSms. - At runtime, Java chooses the method based on the actual object type.
- 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);
}
}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();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");
}
}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?
| The method | What happens? |
|---|---|
final | Cannot be overridden because the parent class fixed the behavior. |
private | The subclass cannot see the method, so a matching subclass method would be new rather than an override. |
static | Not overridden. A matching subclass method hides the parent's static method. |
| Instance method | Can 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() { }
}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();Tėvo statinis metodas
Tėvo statinis metodas
Vaiko statinis metodas
Vaiko egzemplioriaus metodas
staticmethod belongs to the class, so the clearest call uses the class name directly:Tevas.rodytiTipa()orVaikas.rodytiTipa().- Java also lets you write
objektas.rodytiTipa(), even thoughobjektasis a reference variable. This works but is misleading and discouraged. - When a static method is called through a reference, Java considers the declared reference type,
Tevas, rather than the actual object, and therefore runsTevas.rodytiTipa(). Vaikas.rodytiTipa()explicitly selects the static method defined in theVaikasclass.rodytiBusena()is an instance method, so Java considers the actual object,Vaikas, and runs its overridden version.
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());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.
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
| Property | Overloading | Overriding |
|---|---|---|
| English term | overloading | overriding |
| Where does it occur? | Usually in the same class | Between a parent class and a subclass |
| Parameters | Must differ | Must match |
| Selection time | At compile time | At runtime, based on the actual object |
| Purpose | The same action for different arguments | A more specific implementation of inherited behavior |
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,privateandstaticmethods are not overridden.- With
super.metodas()lets you reuse and extend parent behavior.