Java Unit-3
Java Unit-3
INHERITANCE
1. What is inheritance?
Inheritance in Java is a mechanism in which one object acquires(inherits/derives) all the
properties and behaviors of a parent object. It is an important part of OOPs (Object Oriented
programming system).
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 variables of
the parent class. Moreover, you can add new methods and variables in your current class also.
Inheritance represents the IS-A relationship which is also known as a parent-child relationship.
Uses of inheritance in java
1. For Method Overriding (so runtime polymorphism can be achieved).
2. For Code Reusability.
Terms used in Inheritance
Class: A class is a group of objects which have common properties. It is a template or
blueprint from which objects are created.
Sub Class/Child Class: Subclass is a class which inherits the other class. It is also called
a derived class, extended class, or child class.
Super Class/Parent Class: Super class is the class from where a subclass inherits the
features. It is also called a base class or a parent class.
Reusability: As the name specifies, reusability is a mechanism which facilitates you to
reuse the fields and methods of the existing class when you create a new class. You can use the
same fields and methods already defined in the previous class.
Syntax of Java Inheritance
1. class Subclass-name extends Superclass-name
2. {
3. //methods and fields
4. }
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. In Java, a class which is
inherited is called a parent or superclass, and the new class is called child or subclass.
Java Inheritance Example
As displayed in the below figure, Programmer is the subclass and Employee is the
superclass. The relationship between the two classes is Programmer IS-A Employee. It means
that Programmer is a type of Employee.
1. /* Example Program on java inheritance */
2. class Employee{
3. float salary=40000;
4. }
5. class Programmer extends Employee{
6. int bonus=10000;
7. public static void main(String args[]){
8. Programmer p=new Programmer();
9. System.out.println("Programmer salary is:"+p.salary);
10. System.out.println("Bonus of Programmer is:"+p.bonus);
11. }
12. }
Output :
Programmer salary is:40000.0
Bonus of programmer is:10000
In the above example, Programmer object can access the field of own class as well as of
Employee class i.e. code reusability.
Types of inheritance in java
As shown in the figure given above, a class extends another class, an interface extends another
interface, but a class implements an interface.