Class Inheritance
Inheritance Allows you to inherit Properties and Methods from a Parent Class and also Add More, this can make your code Reusable.
Uses of Inheritance
- Child Class Inherits properties and methods from parent class, makes your code Reusable. Since you can also add your own functionalities in the child class, you can inherit only the useful functionalities and define other required features.
- Once any Functionality is developed, you can simply inherit it, this make code cleaner and easier to maintain.
Declaring Class Inheritance
To Inherit Class, extends keyword is used.
Syntax
Example
Here,
We have declared a Parent Class identity with method welcomeText .
We have also declared a child class with name person inherited from identity. and student is an object.
In the child class we have declared age to understand that person class holds its own and its parent class properties and methods.
Super() Keyword
super keyword is used to denote to parent Class. it is used inside child class.
Syntax
Example
Here,
We have declared a Parent Class identity with method welcomeText .
We have also declared a child class with name person inherited from identity. and student is an object.
In the child class, we have used super because when the constructor of class person is called it will also call the constructor of identity class.
You can also override the predefined methods and properties of parent class by assigning the properties and methods with same name in child class.