Inheritance in Java
- You might have heard people saying your nose is similar to your father or mother. Or, more formally, we can say that you've inherited the genes from your parents due to which you look similar to them.
- The same phenomenon of inheritance is also valid in programming.
- In Java, one class can easily inherit the attributes and methods from some other class. This mechanism of acquiring objects and properties from some other class is known as inheritance in Java.
- Inheritance is used to borrow properties & methods from an existing class.
- Inheritance helps us create classes based on existing classes, which increases the code's reusability.
Examples :
Important terminologies used in Inheritance :
- Parent class/superclass: The class from which a class inherits methods and attributes is known as parent class.
- Child class/sub-class: The class that inherits some other class's methods and attributes is known as child class.
Extends keyword in inheritance :
- The extends keyword is used to inherit a subclass from a superclass.
Syntax :
Example :
Note: Java doesn't support multiple inheritances, i.e., two classes cannot be the superclass for a subclass.
Quick quiz: Create a class Animal and Derive another class dog from it
No comments:
Post a Comment