Inheritance in Java
Inheritance is an important pillar of
OOP(Object Oriented Programming). It is the mechanism in java by which one
class is allow to inherit the features(fields and methods) of another class.
The idea behind inheritance in Java is that
you can create new classes that are built upon existing classes. When you
inherit from an existing class, you can reuse methods and fields of the parent
class. Moreover, you can add new methods and fields in your current class also.
Inheritance represents the IS-A
relationship which is also known as a parent-child relationship.
Important terminology:
·
Super Class: The class whose features are inherited is
known as super class(or a base class or a parent class).
·
Sub Class: The class that inherits the other class
is known as sub class(or a derived class, extended class, or child class). The
subclass can add its own fields and methods in addition to the superclass
fields and methods.
·
Reusability: Inheritance supports the concept of “reusability”,
i.e. when we want to create a new class and there is already a class that
includes some of the code that we want, we can derive our new class from the
existing class. By doing this, we are reusing the fields and methods of the
existing class.
How to use inheritance in Java
·
The keyword used for inheritance is extends.
Syntax :
class
derived-class extends base-class
{
//method
and fields
}
Why use inheritance in java
- For Method
Overriding (so runtime polymorphism can be achieved).
- For Code
Reusability.
The extends keyword indicates
that you are making a new class that derives from an existing class. The
meaning of "extends" is to increase the functionality.
Java Inheritance Example
inheritance in java programming |
class Employee{
float salary=40000;
}
class Programmer extends Employee{
int bonus=10000;
public static void main(String args[]){
Programmer p=new Programmer();
System.out.println("Programmer salary is:"+p.salary);
System.out.println("Bonus of Programmer is:"+p.bonus);
}
}
Output:
Programmer salary is:4000.0
Bonus of Programmer is:10000
Type of inheritance in java
There are three types
of inheritance in java:
1) single
2) multilevel
3) hierarchical.
No comments:
Post a Comment