How to Use Inheritance in Java: Syntax and Examples
In Java,
inheritance allows a class to acquire properties and methods from another class using the extends keyword. This helps reuse code and create a hierarchy where the child class inherits from the parent class.Syntax
Inheritance in Java is done by using the extends keyword. The child class inherits fields and methods from the parent class.
- Parent class: The class whose properties are inherited.
- Child class: The class that inherits from the parent.
- extends keyword: Used to declare inheritance.
java
class Parent { void show() { System.out.println("Parent class method"); } } class Child extends Parent { void display() { System.out.println("Child class method"); } }
Example
This example shows a Child class inheriting the show() method from the Parent class and adding its own method display(). When run, it calls both methods.
java
class Parent { void show() { System.out.println("Parent class method"); } } class Child extends Parent { void display() { System.out.println("Child class method"); } } public class Main { public static void main(String[] args) { Child obj = new Child(); obj.show(); // inherited method obj.display(); // own method } }
Output
Parent class method
Child class method
Common Pitfalls
Common mistakes when using inheritance include:
- Trying to inherit from multiple classes (Java does not support multiple inheritance with classes).
- Not calling the parent constructor properly when needed.
- Overriding methods without using
@Overrideannotation, which can cause errors. - Accessing private members of the parent class directly (they are not inherited).
java
class Parent { private void secret() { System.out.println("Secret method"); } } class Child extends Parent { void tryAccess() { // secret(); // Error: cannot access private method } } // Correct way is to use protected or public methods in parent for inheritance.
Quick Reference
| Concept | Description |
|---|---|
| extends | Keyword to inherit from a parent class |
| super() | Call parent class constructor |
| @Override | Annotation to override parent method |
| Single inheritance | Java supports one parent class per child |
| private members | Not accessible in child class |
Key Takeaways
Use the extends keyword to inherit from a parent class in Java.
Child classes inherit accessible fields and methods from the parent class.
Java supports single inheritance; multiple inheritance with classes is not allowed.
Use @Override annotation when redefining parent methods to avoid mistakes.
Private members of the parent class are not accessible in the child class.