Java Inheritance
Inheritance Basics
• Inheritance enables hierarchical class
structures.
• Subclass inherits fields and methods from
superclass.
• Syntax: class Triangle extends TwoDShape
{ ... }
• Promotes code reuse and logical modeling.
Types of Inheritance in Java
• ✔ Single Inheritance
• ✔ Multilevel Inheritance:
class C extends B extends A
• ✔ Hierarchical Inheritance
• ✘ Multiple Inheritance not supported via
classes (use interfaces)
Example – TwoDShape & Triangle
• class TwoDShape { double width, height; void
showDim() { ... } }
• class Triangle extends TwoDShape {
String style;
double area() { return width * height / 2; }
}
The super Keyword
• Used to call superclass constructor:
super(width, height);
• Used to access hidden superclass members:
super.showDim();
• Resolves naming conflicts and reuses parent
logic.
Method Overriding
• Subclass redefines method with same
signature:
• class A { void show() { ... } }
• class B extends A { void show() { ... } }
• Use super.show() to call overridden version.
Dynamic Method Dispatch
• Superclass reference refers to subclass object:
• A a; B b = new B(); a = b; a.show();
• Calls subclass method at runtime.
• Enables runtime polymorphism.
Abstract Classes & Methods
• Abstract class: can't be instantiated directly.
• Contains abstract methods with no body.
• abstract class Shape { abstract double area(); }
• Forces subclasses to define abstract methods.
Example – Abstract area()
abstract class TwoDShape {
double width, height;
abstract double area();
}
class Triangle extends TwoDShape {
double area()
{
return width * height / 2;
}
}
Final Keyword
• final method: cannot be overridden.
• final class: cannot be subclassed.
• final variable: becomes a constant.
• Usage:
final class A { ... }
final void meth() { ... }
Summary
• ✔ Inheritance models 'is-a' relationships
• ✔ super builds on inherited logic
• ✔ Overriding enables polymorphism
• ✔ Abstract class enforces implementation
contracts
• ✔ final protects methods, classes, and
constants