Inheritance can be defined as the process where one class acquires the properties (methods and fields) of another. With the use of inheritance the information is made manageable in a hierarchical order.
The class which inherits the properties of other is known as subclass (derived class, child class) and the class whose properties are inherited is known as superclass (base class, parent class).
To inherit the properties of a class, use keyword extends.
Syntax
class Super {
.....
.....
}
class Sub extends Super {
.....
.....
}
In this example, Calculator is a super-class (a parent class) and MyCalculator is a sub-class (a child class). A child class (MyCalculator) is created from a parent class (Calculator), and thus the child class can inherit (methods and fields) from the parent class.
// file name: MyCalculator.java
public class MyCalculator extends Calculator{
public static void main(String[] args) {
// TODO Auto-generated method stub
MyCalculator calc = new MyCalculator();
int a = 2;
int b = 3;
add(a,b);
calc.multiplication(a, b);
calc.subtract(a, b);
}
static void add(int a, int b){
int result = a + b;
System.out.println("Add: " + result);
}
}
// filename: Calculator.java
public class Calculator{
int result = 0;
public Calculator(){
}
public void multiplication(int a, int b){
result = a * b;
System.out.println("Multiplication: " + result);
}
public void subtract(int a, int b){
result = a - b;
System.out.println("Subtract: " + result);
}
}
The main advantages of inheritance are code reusability and readability. When child class inherits the properties and functionality of parent class, we need not to write the same code again in child class. This makes it easier to reuse the code, makes us write the less code and the code becomes much more readable.
Basically, java only uses a single inheritance as a subclass cannot extend more superclass. In single inheritance, a single subclass extends from a single superclass.