INHERITANCE IN JAVA
Inheritance in Java
• Inheritance is one of the key features of OOP (Object-
oriented Programming) that allows us to define a new
class from an existing class.
• Inheritance provided mechanism that allowed a class to
inherit property of another class.
• When a Class extends another class it inherits all non-
private members including fields and methods.
• In Java, we use the “extends” keyword to inherit from a
class.
• For Method Overriding (so runtime polymorphism can be
achieved).
• 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: Superclass 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.
The syntax of Java Inheritance
class Subclass-name extends Superclass-name
{
//methods and fields
}
Ex:
class Vehicle
{
......
}
class Car extends Vehicle
{
....... //extends the property of vehicle class
}
• 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 the terminology of Java, a class which is inherited is
called a parent or superclass, and the new class is called
child or subclass.
Types of inheritance in java
• On the basis of class, there can be three types of inheritance in java:
• Single inheritance - Class B extends from class A only.
• Multilevel inheritance - Class B extends from class A; then class C extends
from class B.
• Hierarchical inheritance - Class A acts as the superclass for classes B, C,
and D.
• In java programming, multiple and hybrid inheritance is supported through
interface only.
• Multiple inheritance - Class C extends from interfaces A and B.
• Hybrid inheritance - Mix of two or more types of inheritance.