Description
Inheritance is a fundamental OOP concept in Java that allows a class to inherit properties and methods from another class. It promotes code reusability and establishes an “is-a” relationship between classes.
Key Concepts
Basic Inheritance
- A subclass (child class) extends a superclass (parent class)
- The subclass inherits all non-private fields and methods from the superclass
- Java supports single inheritance (one parent class per child)
- Use the
extends keyword to establish inheritance
Inheritance Hierarchy
- Object class: All classes implicitly extend Object
- Single inheritance: A class can only extend one parent class
- Multi-level inheritance: Class A extends B, B extends C
- Method overriding: Subclasses can override parent methods
Access Modifiers and Inheritance
- public: Inherited and accessible everywhere
- protected: Inherited and accessible in subclass and same package
- private: Not inherited, only accessible in defining class
- default (package-private): Inherited if in same package
Method Overriding
- Subclass provides its own implementation of a parent method
- Must have same signature (name, parameters, return type)
- Use
@Override annotation for safety - Cannot override static, final, or private methods
- Access modifier cannot be more restrictive
Benefits
- Code reuse: Share common code between classes
- Polymorphism: Treat objects of different types uniformly
- Extensibility: Add new functionality without modifying existing code
- Maintainability: Centralize common logic in parent class
Best Practices
- Use inheritance for “is-a” relationships
- Prefer composition over inheritance when appropriate
- Keep inheritance hierarchies shallow
- Make classes final if they shouldn’t be extended
- Use abstract classes for shared implementations
Common Patterns
- Abstract classes: Define common structure with some implementation
- Final classes: Prevent further inheritance
- Super keyword: Access parent class members
- Constructor chaining: Call parent constructor using super()
Comments
No comments yet. Be the first!
Please login to leave a comment.