Inheritance in java
1. The process of getting the property of one class into another class is called Inheritance.
2. In other words we can say that the process of deriving a new class from an old class is called inheritance in which the new class is called derived or child or subclass and the old class is called Base or Parent or Superclass.
3. When a class inherits the property of a class it means it can access all the data member and member functions of that class except the private element.
4. In this type of programming mainly two types of classes are used.
- Parent/Super/Base class
- Child/Sub/Derived class
Parent/Super/Base class
The class which is inherited by another class is called Parent or Super or Base class.
Child/Sub/Derived class
The class which inherits the property of another class is called Child or Sub or Derived class.
The derived class extends the Base class
Example:
class Subtraction extends Addition
Here Subtraction is a Derived class Addition is a Base class and extends is a keyword that is used to inherit one class into another.
1: //Base class
2: class Addition
3: {
4: void add()
5: {
6: int x,y=30,z=10;
7: x=y+z;
8: System.out.println("Add="+x);
9: }
10: }
11: //Derived class extending base class
12: class Subtraction extends Addition
13: {
14: void sub()
15: {
16: int x,y=30,z=10;
17: x=y-z;
18: System.out.println("Sub="+x);
19: }
20: }
21: class Easy
22: {
23: public static void main(String[] args)
24: {
25: //Creating instance(object)
26: Subtraction obj=new Subtraction();
27: //calling base class method
28: obj.add();
29: //calling derived class method
30: obj.sub();
31: }
32: }
33: /*
34: ### Output ###
35: Add=40
36: Sub=20
37: */
Here class Addition is a base class and Subtraction is a derived class because Addition is inherited into Subtraction therefore we can call all the functions using the object of Subtraction.
Read more: Click Here