Polymorphism in java
Polymorphism means "one thing, many forms." A parent class reference can refer to different child class objects, and Java calls the appropriate overridden method.
class Bicycle {
void printDescription() {
System.out.println("This is a bicycle");
}
}
class MountainBike extends Bicycle {
@Override
void printDescription() {
System.out.println("This is a mountain bike");
}
}
class RoadBike extends Bicycle {
@Override
void printDescription() {
System.out.println("This is a road bike");
}
}
public class Main {
public static void main(String[] args) {
Bicycle bike1 = new Bicycle();
Bicycle bike2 = new MountainBike();
Bicycle bike3 = new RoadBike();
bike1.printDescription();
bike2.printDescription();
bike3.printDescription();
}
}
Output:
This is a bicycle
This is a mountain bike
This is a road bike
Key point: The reference type is Bicycle, but Java runs the method based on the actual object (MountainBike or RoadBike).
Field Hiding
If a child class has a field with the same name as its parent, the child's field hides the parent's field.
class Parent {
int value = 10;
}
class Child extends Parent {
int value = 20;
}
Generally, avoid field hiding because it can make code confusing.
super Keyword
super is used to access parent class members.
Calling a parent method
class Parent {
void show() {
System.out.println("Parent");
}
}
class Child extends Parent {
@Override
void show() {
super.show();
System.out.println("Child");
}
}
Output:
Parent
Child
Calling a parent constructor
class Parent {
Parent(int x) {
System.out.println(x);
}
}
class Child extends Parent {
Child() {
super(10);
}
}
Important: super(...) must be the first statement in a child constructor.
If you don't write super(), Java automatically calls the parent's no-argument constructor (if one exists).
This is called constructor chaining.
final Methods and Classes
final method
A final method cannot be overridden.
class Parent {
final void show() {
System.out.println("Hello");
}
}
class Child extends Parent {
// ERROR
void show() {}
}
final class
A final class cannot be extended.
final class Animal {
}
// ERROR
class Dog extends Animal {
}
Easy rule:
final method→ cannot override
final class→ cannot extend