Inheritance in Java allows one class to acquire the properties (fields) and behaviors (methods) of another class.
Superclass(Parent/Base Class): The existing class.
Subclass (Child/Derived Class): The new class that inherits features from the superclass. It can reuse, modify, or add its own variables and methods.
extends Keyword: The Java keyword used to create a subclass.
Types of Inheritance
- Single Inheritance : A subclass inherits from exactly one superclass.
EX: Class A → Class B
- Multilevel Inheritance : A class inherits from a subclass, creating a chain of inheritance.
EX: Class A → Class B → Class C
- Hierarchical Inheritance : Multiple subclasses inherit from the same single superclass.
EX: Class A → Class B & Class C
Example Code
// Superclass(Parent/Base Class)
package thanjavur;
public class RajaRajaChola
{
public void abdication(){
System.out.println("The king gives the throne to Prince");
}
}
// Subclass (Child/Derived Class)
package gangaikondaCholapuram;
import thanjavur.RajaRajaChola;
public class RajendraChola extends RajaRajaChola
{
public static void main(String[] args)
{
RajendraChola coronation = new RajendraChola();
coronation.abdication();
}
}


Top comments (0)