Inheritance lets a class (the subclass or child) reuse and extend another class (the superclass or parent) using extends. It models an is-a relationship: a Manager is an Employee; a SavingsAccount is an Account.
extends and super#
Hi, I am Kavya, 20 years old. Kavya is studying B.Tech CSE
- The child gets all non-private fields and methods of the parent.
super(...)calls the parent constructor (first line of the child constructor). If you leave it out, Java insertssuper()automatically - which fails if the parent has no no-argument constructor.protectedmembers are accessible in subclasses.
extends से child class को parent class की चीज़ें मिल जाती हैं। Child के constructor में सबसे पहले super(...) से parent का constructor चलता है, ताकि parent वाला हिस्सा (name, age) पहले तैयार हो जाए। Java में एक class सिर्फ़ एक class को extend कर सकती है।
Method overriding#
A subclass can provide its own version of an inherited method. Mark it with @Override so the compiler checks the signature:
Employee Amit 78000.00 Manager Sunita 132000.00 Intern Yash 15000.00 Total payroll: 225000.00
Polymorphism#
That loop is polymorphism: the variable type is Employee, but each object runs its own monthlyPay() and role(). In Java every non-static, non-private, non-final method is virtual, so the version is chosen at run time from the real object (dynamic method dispatch).
Circle with area 12.57 Rectangle with area 13.50 true Pattern variable c: Circle
| Overloading | Overriding | |
|---|---|---|
| Where | same class | parent and child |
| Signature | different parameters | same parameters |
| Decided | at compile time | at run time |
| Kind of polymorphism | static | dynamic |
final, and what cannot be overridden#
- A
finalmethod cannot be overridden; afinalclass cannot be extended (Stringis final). staticmethods are not overridden (a child static method with the same name only hides the parent's).privatemethods are not inherited, so they cannot be overridden.- An overriding method cannot reduce visibility (a
publicmethod cannot becomeprivate).
The Object class#
Every class extends java.lang.Object, which provides toString(), equals(), hashCode(), getClass() and more:
Book true true
Summary#
class Child extends Parentreuses fields and methods; Java allows one parent class.super(...)calls the parent constructor;super.method()calls the parent's version.@Overrideredefines inherited methods; calls through parent references use the real object's version (polymorphism).finalblocks overriding/extension; every class ultimately extendsObject.