Inheritance in Java - Notes
Inheritance in Java
What is Inheritance?
Inheritance is a key concept of Object-Oriented Programming (OOP) where one class (child) inherits fields
and methods from another class (parent).
Why Use Inheritance?
- Code Reusability
- Avoids Duplication
- Enables Method Overriding
- Simplifies Code Hierarchy
Syntax:
class Parent {
// parent methods and properties
class Child extends Parent {
// child inherits from parent
Example:
class Animal {
void eat() {
System.out.println("I can eat");
class Dog extends Animal {
void bark() {
Inheritance in Java - Notes
System.out.println("I can bark");
Types of Inheritance in Java:
1. Single Inheritance -> Supported
2. Multilevel Inheritance -> Supported
3. Hierarchical Inheritance-> Supported
4. Multiple Inheritance -> Not supported directly (Java avoids diamond problem)
5. Hybrid Inheritance -> Not supported directly
Method Overriding:
class Animal {
void sound() {
System.out.println("Some sound");
class Dog extends Animal {
@Override
void sound() {
System.out.println("Dog barks");
Real-world Example:
class Employee {
String name;
void work() {
System.out.println(name + " is working");
}
Inheritance in Java - Notes
class Manager extends Employee {
void manage() {
System.out.println(name + " is managing team");
Notes:
- Use 'extends' keyword for inheritance.
- Private members of parent class are not directly accessible.
- Constructors are not inherited but can be accessed using super().