Java Tutorial
🔍
What is OOP?Classes & ObjectsConstructorsAccess Modifiersthis Keywordstatic KeywordEncapsulationInheritancesuper KeywordMethod OverridingOverloading vs OverridingPolymorphismUpcasting & Downcastinginstanceof OperatorAbstractionAbstract ClassesInterfacesMarker InterfacesAbstract Class vs InterfaceObject ClasstoString() Methodequals() & hashCode()
Collections OverviewCollections HierarchyIterable InterfaceCollection InterfaceMap Interfaceequals() and hashCode()IteratorListIteratorFail-fast vs Fail-safe IteratorConcurrentModificationExceptionArrayListLinkedListHashSetLinkedHashSetTreeSetQueuePriorityQueueDequeArrayDequeHashMapLinkedHashMapTreeMapConcurrentHashMapCopyOnWriteArrayListList vs Set vs MapChoosing the Right CollectionComparableComparatorComparable vs ComparatorCollections Utility ClassArrays Utility ClassImmutable CollectionsCollection vs CollectionsVectorHashtableStackArrayList Internal WorkingLinkedList Internal WorkingHashMap Internal WorkingTreeMap Internal Working
Inheritance & Method Overriding in Java
intermediate· OOP · Inheritance
Problem
Method overriding lets a subclass provide its own implementation of a method already defined in its parent class.
Create a base Animal class and a Dog subclass that overrides its behavior.
Java Program
Java
class Animal {
void sound() {
System.out.println("The animal makes a sound");
}
}
class Dog extends Animal {
@Override
void sound() {
// Overrides Animal's version with Dog-specific behavior
System.out.println("The dog barks");
}
}
public class InheritanceDemo {
public static void main(String[] args) {
// Declared as Animal, but the actual object is a Dog
Animal a = new Dog();
// Java resolves sound() using the object's real (runtime) type
a.sound();
}
}Output
The dog barks
Core Logic
This is runtime polymorphism in action — a subclass overrides a parent method, and Java picks the subclass's version even when the reference is typed as the parent.
How It Works
- 1
class Dog extends AnimalmakesDoga subclass that inherits everythingAnimaldefines. - 2
@Override void sound()replaces the inherited method with Dog-specific behavior; the annotation lets the compiler catch signature mismatches. - 3
Animal a = new Dog();declares the variable as typeAnimal, but the object it points to is actually aDog. - 4When
a.sound()is called, Java resolves the method using the object's actual runtime type, not the variable's declared type.
Even though
a is declared Animal, calling a.sound() prints "The dog barks", not a generic Animal message.💡
Key Point: This is dynamic method dispatch — the JVM decides which overridden method to run based on the object's real class, at runtime.
Key Concepts
extends@Overrideruntime polymorphism