OBJECT-ORIENTED PROGRAMMING
Java polymorphism
Polymorphism means “many forms”. It lets you use objects of different subclasses through a common base type, with each object handling the same method call differently.
Inheritance and polymorphism
Inheritance connects a base class to its subclasses. Polymorphism uses that connection: a base-class reference can point to different subclass objects, and an overridden method is chosen based on the actual object.
Different behavior for the same method
Books, magazines and newspapers are publications, but each introduces itself differently:
class Leidinys {
public void rodytiTipa() {
System.out.println("Tai yra leidinys");
}
}
class Knyga extends Leidinys {
@Override
public void rodytiTipa() {
System.out.println("Tai yra knyga");
}
}
class Zurnalas extends Leidinys {
@Override
public void rodytiTipa() {
System.out.println("Tai yra žurnalas");
}
}
class Laikrastis extends Leidinys {
@Override
public void rodytiTipa() {
System.out.println("Tai yra laikraštis");
}
}Leidinysis a shared base class with the methodrodytiTipa().Knyga,ZurnalasandLaikrastisextend this class.- Each subclass overrides the same method and produces its own result.
- This block creates no objects and calls no methods yet, so nothing appears in the console.
A base-class reference
public class Main {
public static void main(String[] args) {
Leidinys pirmas = new Leidinys();
Leidinys antras = new Knyga();
Leidinys trecias = new Zurnalas();
pirmas.rodytiTipa();
antras.rodytiTipa();
trecias.rodytiTipa();
}
}Tai yra leidinys
Tai yra knyga
Tai yra žurnalas
- All three variables are declared with the common type
Leidinys. - However,
antrasstores an actualKnyga, whiletrecias–Zurnalasobject. - At runtime, Java looks at the actual object and selects its
rodytiTipa()version. - Identically written method calls therefore produce different results.
Different objects in one array
A common type lets one collection hold objects of different subclasses:
public class Main {
public static void main(String[] args) {
Leidinys[] leidiniai = {
new Knyga(),
new Zurnalas(),
new Laikrastis()
};
for (Leidinys leidinys : leidiniai) {
leidinys.rodytiTipa();
}
}
}Tai yra knyga
Tai yra žurnalas
Tai yra laikraštis
Leidinys[]array can hold all objects that are instances ofLeidinysor its subclasses.for-eachloop takes one publication at a time.- The loop does not need to check whether an element is a book, magazine or newspaper.
- Each object runs its own overridden method.
A common method parameter
A method accepting a base type can work with any of its subclasses:
public class Main {
static void pristatyti(Leidinys leidinys) {
leidinys.rodytiTipa();
}
public static void main(String[] args) {
pristatyti(new Knyga());
pristatyti(new Laikrastis());
}
}Tai yra knyga
Tai yra laikraštis
- The method
pristatyti()accepts a parameter of the commonLeidinystype. - It can receive either
KnygaandLaikrastisobject. - Adding a new publication subclass usually requires no changes to the method
pristatyti()itself.
Reference type and object type
class Knyga extends Leidinys {
public void atverstiPuslapi() {
System.out.println("Puslapis atverstas");
}
}
public class Main {
public static void main(String[] args) {
Leidinys leidinys = new Knyga();
leidinys.rodytiTipa();
// leidinys.atverstiPuslapi(); // Compilation error
}
}Tai yra knyga
The object is actually a Knyga, so the book's overridden method runs. However, the reference is declared as Leidinys, so it cannot directly call the book-only method atverstiPuslapi().
| Type | What does it determine? |
|---|---|
| Declared reference type | Which members the compiler allows access to |
| Actual object type | Which overridden method implementation runs |
Be careful with casting
You can try casting a base-class reference to a subclass, but the object must actually have that type:
Leidinys leidinys = new Zurnalas();
// Runtime error: the object is not a Knyga
Knyga knyga = (Knyga) leidinys;java.lang.ClassCastException: Zurnalas cannot be cast to Knyga
- The variable
leidinysactually stores aZurnalasobject. - Writing a type in parentheses does not turn a magazine into a book.
- The program compiles, but the invalid assumption is detected at runtime.
- Well-designed polymorphic code often needs no such cast.
Why use polymorphism?
- One piece of code can process many related object types.
- New subclasses can be added with fewer changes to existing code.
- Type checks and long
if...elsechains often become unnecessary. - Each class is responsible for its own method implementation.
- The inherited common interface and specialized behavior remain clearly separated.