Java Inheritance (IS-A)
Syntax
class ChildClass extends ParentClass {
// child class methods and variables
}
Example
A Bird
class extending Animal
class to inherit its properties.
class Animal {
public void eat() {
System.out.println("Animal is eating");
}
}
class Bird extends Animal {
public void fly() {
System.out.println("Bird is flying");
}
}
Output
Animal is eating
Bird is flying
Explanation
In Java, inheritance is a mechanism that enables one class to inherit the properties and methods of another. The extends
keyword is used to indicate that one class is inheriting from another class. The class that is being inherited from is known as the superclass or parent class. The class that is inheriting is known as the subclass or child class.
The child class can access all the public and protected methods and variables of the parent class. In other words, the child class has access to all the non-private members of the parent class.
Use
Inheritance is a powerful feature in Java that allows developers to reuse code and organize their program in a more hierarchical way. Inheritance is useful when you have classes that share properties and behaviors. Instead of writing the same code multiple times, you can create a parent class with the shared properties and behaviors, and then create child classes that inherit from the parent class.
Important Points
- The
extends
keyword is used for inheritance in Java. - Subclasses inherit all the public and protected methods and variables of the parent class.
- Inheritance is a powerful feature that allows developers to reuse code and organize their program in a more hierarchical way.
Summary
Inheritance is a fundamental concept in Java programming. It allows developers to reuse code and organize their program in a more hierarchical way. Inheritance is useful when you have classes that share properties and behaviors. The subclass inherits all the public and protected methods and variables of the parent class. Inheritance is a powerful feature that can simplify code and make it more efficient.