Download as docx, pdf, or txt
Download as docx, pdf, or txt
You are on page 1of 13

Inheritance in Java

Inheritance in Java is a mechanism in which one object acquires all the properties
and behaviours 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 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.

Terms Used in Inheritance

Class: A class is a collection of objects which have common properties.

Derived Class/Sub-class: Derived class is a class that inherits from a base class. It is
also known as subclass or child class.

Base Class/Superclass: The base class is the main class where derived classes inherit
the features. It is also known as the superclass or parent class.

Reusability: The name itself says reuse the repeated code in the programs. It is a
mechanism to reuse existing code when you are creating new classes.

Syntax

The basic syntax is


Class superclass {
—————-
}

class subclass extends superclass


{
————–
—————–
}

The keyword “extends” is used while inheriting a class. It defines that the
functionality of the superclass is being extended to the subclass.
The new class created is called a sub-class while the inherited class is termed a
parent

Java Inheritance Example

As displayed in the above 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.

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);

} }

Programmer salary is:40000.0


Bonus of programmer is:10000

Types of inheritance in java


On the basis of class, there can be three types of inheritance in java: single,
multilevel and hierarchical.

In java programming, multiple and hybrid inheritance is supported through interface


only. We will learn about interfaces later.

Single Inheritance Example

When a class inherits another class, it is known as a single inheritance.


Single inheritance enables a derived class to inherit properties and behavior from a
single parent class. It allows a derived class to inherit the properties and behavior of
a base class, thus enabling code reusability as well as adding new features to the
existing code. This makes the code much more elegant and less repetitive.

Benefits and Limitations of Single Inheritance in Java

Single inheritance in Java has several benefits and limitations. Here are some of
them:
Benefits:

● It makes code easier to understand and manage by maintaining a


hierarchical structure. Code duplicity is also reduced.
● Code reusability, as a derived class, can inherit the properties, behaviours
and methods from the parent class.
● A higher level of abstraction, as the derived class can add its own
methods and properties with the addition of the properties inherited
from the parent class.
Limitations:

● a class can only inherit from a single parent which results in less flexibility
for class designs.
● limit the ability to reuse code as some code might not fit in a hierarchy
caused due to single inheritance.
● This can cause ambiguity in code or throw errors, as some inherited
methods can have the same names but have different operations.

class Shape {

// calculateArea is member of shape class


public int calculateArea(int length,int breadth) {
return length * breadth;
}
}

// Inheriting Shape member using extends keyword


class Rectangle extends Shape {

public static void main(String[] args) {


Rectangle rectangle = new Rectangle(); // creating object of child class
System.out.println("Area of rectangle :: "+ rectangle.calculateArea(10,5)); //
calcualateArea method accessible to rectangle class
} }
# Java program to print student details using "single-level" inheritance

import java.util.Scanner;
public class SingleInherit {
int rollno;
String name;
String college;
Scanner sc = new Scanner(System.in);
void input() {
System.out.print("Enter Roll Number: ");
rollno=sc.nextInt();
System.out.println("Enter Student Name");
name = sc.next();
System.out.println("Enter College Name");
college = sc.next();
}
}
class Department extends SingleInherit
{
void display()
{
String deptname ;
String classname;
System.out.println("Enter Department name");
deptname=sc.next();
System.out.println("Enter Class Name");
classname=sc.next();
System.out.println("Student Roll No: " +rollno);
System.out.println("Student Name: "+ name);
System.out.println("College Name: " +college);
System.out.println("Department Name: "+deptname);
System.out.println("Class Name :"+ classname);
}
public static void main(String [] args)
{
Department d= new Department();
d.input();
d.display();
}
}

Super Keyword in Java


The super keyword in Java is a reference variable which is used to refer immediate
parent class object.

Whenever you create the instance of subclass, an instance of parent class is created
implicitly which is referred by super reference variable.

Characteristics of Super Keyword in Java


In Java, super keyword is used to refer to the parent class of a subclass. Here are
some of its characteristics:
● super is used to call a superclass constructor: When a subclass is created,
its constructor must call the constructor of its parent class. This is done
using the super() keyword, which calls the constructor of the parent class.
● super is used to call a superclass method: A subclass can call a method
defined in its parent class using the super keyword. This is useful when the
subclass wants to invoke the parent class’s implementation of the method
in addition to its own.
● super is used to access a superclass field: A subclass can access a field
defined in its parent class using the super keyword. This is useful when the
subclass wants to reference the parent class’s version of a field.
● super must be the first statement in a constructor: When calling a
superclass constructor, the super() statement must be the first statement
in the constructor of the subclass.
● super cannot be used in a static context: The super keyword cannot be
used in a static context, such as in a static method or a static variable
initializer.
● super is not required to call a superclass method: While it is possible to use
the super keyword to call a method in the parent class, it is not required. If
a method is not overridden in the subclass, then calling it without the
super keyword will invoke the parent class’s implementation.

Overall, the super keyword is a powerful tool for subclassing in Java, allowing
subclasses to inherit and build upon the functionality of their parent classes.
Use of super keyword in Java
It is majorly used in the following contexts as mentioned below:
● Use of super with variables
● Use of super with methods
● Use of super with constructors

1. Use of super with Variables


This scenario occurs when a derived class and base class has the same data
members. In that case, there is a possibility of ambiguity for the JVM.
We can understand it more clearly using the following example:
Example

// Java code to show use of super keyword with variables


// Base class vehicle
class Vehicle {
int maxSpeed = 120;
}
// sub class Car extending vehicle
class Car extends Vehicle {
int maxSpeed = 180;
void display()
{
// print maxSpeed of base class (vehicle) System.out.println("Maximum Speed: "
super.maxSpeed);
}
}
// Driver Program
class Test {
public static void main(String[] args) {
Car small = new Car();
small.display();
}}

In the above example, both the base class and subclass have a member maxSpeed. We
could access maxSpeed of base class in subclass using super keyword.

2. Use of super with Methods

This is used when we want to call the parent class method. So whenever a parent and
child class have the same-named methods then to resolve ambiguity we use the super
keyword.
This code snippet helps to understand the said usage of the super keyword.
Example
// Java program to show use of super with methods
// superclass Person
class Person {
void message()
{
System.out.println("This is person class\n");
}
}
// Subclass Student
class Student extends Person {
void message()
{
System.out.println("This is student class");
}
// Note that display() is only in Student class
void display()
{
// will invoke or call current class message() method
message();
// will invoke or call parent class message() method
super.message();
}
}
// Driver Program
class Test {
public static void main(String args[])
{
Student s = new Student();
// calling display() of Student
s.display();
}
}
In the above example, we have seen that if we only call method message() then, the
current class message() is invoked but with the use of the super keyword, message() of
the superclass could also be invoked.

3. Use of super with constructors

The super keyword can also be used to access the parent class constructor. One more
important thing is that ‘super’ can call both parametric as well as non-parametric
constructors depending on the situation.
Following is the code snippet to explain the above concept:
Example 1
// Java Code to show use of super keyword with constructor
// superclass Person
class Person {
Person()
{
System.out.println("Person class Constructor");
}
}
// subclass Student extending the Person class
class Student extends Person {
Student()
{
// invoke or call parent class constructor
super();
System.out.println("Student class Constructor");
}
}
// Driver Program
class Test {
public static void main(String[] args)
{
Student s = new Student();
} }
In the above example, we have called the superclass constructor using the keyword
‘super’ via subclass constructor.

Advantages of Using Java super keyword

The super keyword in Java provides several advantages in object-oriented programming:


● Enables reuse of code: Using the super keyword allows subclasses to inherit
functionality from their parent classes, which promotes the reuse of code and
reduces duplication.
● Supports polymorphism: Because subclasses can override methods and access
fields from their parent classes using super, polymorphism is possible. This
allows for more flexible and extensible code.
● Provides access to parent class behavior: Subclasses can access and use
methods and fields defined in their parent classes through the super keyword,
which allows them to take advantage of existing behavior without having to
reimplement it.
● Allows for customization of behavior: By overriding methods and using super
to call the parent implementation, subclasses can customize and extend the
behavior of their parent classes.
● Facilitates abstraction and encapsulation: The use of super promotes
encapsulation and abstraction by allowing subclasses to focus on their own
behavior while relying on the parent class to handle lower-level details.

Inheritance and Constructors in Java


Constructors in Java are used to initialize the values of the attributes of the object serving
the goal to bring Java closer to the real world. We already have a default constructor that
is called automatically if no constructor is found in the code. But if we make any
constructor say parameterized constructor in order to initialize some attributes then it
must write down the default constructor because it now will be no more automatically
called.
Note: In Java, constructor of the base class with no argument gets automatically called in
the derived class constructor.

Ex
// Java Program to Illustrate Invocation of Constructor Calling Without Usage of // super
Keyword
// Class 1 Super class
class Base {
// Constructor of super class
Base()
{
// Print statement
System.out.println("Base Class Constructor Called ");
}}
// Class 2 Sub class
class Derived extends Base {

// Constructor of sub class


Derived()
{
// Print statement
System.out.println("Derived Class Constructor Called ");
} }
// Class 3 Main class
class GFG {
public static void main(String[] args)
{
// Creating an object of sub class inside main() method
Derived d = new Derived();
}
}
Note: Here first super class constructor will be called there after derived(sub class)
constructor will be called

Output Explanation: Here first superclass constructor will be called thereafter


derived(sub-class) constructor will be called because the constructor call is from top to
bottom. And yes if there was any class that our Parent class is extending then the body of
that class will be executed thereafter landing up to derived classes.
But, if we want to call a parameterized constructor of the base class, then we can call it
using super(). The point to note is base class constructor call must be the first line in the
derived class constructor.
Implementation: super(a) is the first line-derived class constructor.
// Java Program to Illustrate Invocation of Constructor Calling With Usage
// of super Keyword

// Class 1 Super class


class Base {
int x;
// Constructor of super class
Base(int a)
{
x = a;
}
}

// Class 2 Sub class


class Derived extends Base {
int y;
// Constructor of sub class
Derived(int a, int b)
{

// super keyword refers to super class


super(a);
y = b;
}

// Method of sub class


void Display()
{
// Print statement
System.out.println("x = " + x + ", y = " + y);
}
}

// Class 3
// Main class
public class GFG {

// Main driver method


public static void main(String[] args)
{
// Creating object of sub class inside main() method
Derived d = new Derived(10, 20);

// Invoking method inside main() method


d.Display();
}
}

You might also like