Keyboard shortcuts

Press or to navigate between chapters

Press S or / to search in the book

Press ? to show this help

Press Esc to hide this help

AspectInheritancePolymorphism
DefinitionA mechanism where a class (subclass) inherits fields and methods from another class (superclass).A mechanism allowing objects of different classes to be treated as instances of a common superclass or interface.
PurposeEnables code reuse and establishes an “is-a” relationship between classes.Enables flexibility by allowing a single interface to represent different types or behaviors.
MechanismAchieved using the extends keyword for classes or implements for interfaces.Achieved through method overriding (runtime) or method overloading (compile-time).
RelationshipCreates a hierarchical relationship (e.g., Dog is an Animal).Allows objects to be processed uniformly despite different implementations (e.g., Animal reference for Dog or Cat).
TypeStructural concept (defines class relationships).Behavioral concept (defines how objects behave or are accessed).
Code Examplejava<br>class Animal {<br> void eat() { System.out.println("Eating"); }<br>}<br>class Dog extends Animal {}<br>java<br>class Animal {<br> void sound() { System.out.println("Sound"); }<br>}<br>class Dog extends Animal {<br> @Override<br> void sound() { System.out.println("Woof"); }<br>}<br>Animal a = new Dog();<br>a.sound(); // Outputs: Woof<br>
Execution TimeDetermined at compile time (class structure is fixed).Runtime (method overriding) or compile-time (method overloading).
FlexibilityFixed hierarchy; adding new classes requires modifying the structure.Highly flexible; new subclasses can be added without changing existing code.
DependencyDoes not require polymorphism (can exist without overriding).Often relies on inheritance (for method overriding) or interfaces.
ScopeFocuses on sharing and extending code (fields, methods).Focuses on dynamic behavior or method selection.

Relationship Between Inheritance and Polymorphism

  • Dependency: Polymorphism (specifically runtime polymorphism via method overriding) often relies on inheritance, as it requires a superclass-subclass relationship or interface implementation. However:
    • Inheritance can exist without polymorphism (e.g., a subclass uses inherited methods without overriding them).
    • Polymorphism can occur without inheritance in the case of interfaces (e.g., a class implements an interface but doesn’t extend a class).
  • Complementary Roles:
    • Inheritance provides the structure (class hierarchy) for code reuse.
    • Polymorphism provides the behavior (dynamic method invocation) for flexibility.