0% found this document useful (0 votes)
18 views10 pages

Inheritance in Java

Inheritance in Java allows one class to inherit features from another class. This allows code reusability and abstraction. The key concepts are superclass, subclass, overriding and polymorphism. Constructors are special methods used to initialize objects when they are created.

Uploaded by

mapeda5764
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
Download as docx, pdf, or txt
0% found this document useful (0 votes)
18 views10 pages

Inheritance in Java

Inheritance in Java allows one class to inherit features from another class. This allows code reusability and abstraction. The key concepts are superclass, subclass, overriding and polymorphism. Constructors are special methods used to initialize objects when they are created.

Uploaded by

mapeda5764
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
Download as docx, pdf, or txt
Download as docx, pdf, or txt
You are on page 1/ 10

Inheritance in java

Java, Inheritance is an important pillar of OOP(Object-Oriented Programming). It is


the mechanism in Java by which one class is allowed to inherit the features(fields
and methods) of another class. In Java, Inheritance means creating new classes based
on existing ones. A class that inherits from another class can reuse the methods and
fields of that class. In addition, you can add new fields and methods to your current
class as well.
Why Do We Need Java Inheritance?
 Code Reusability: The code written in the Superclass is common to all
subclasses. Child classes can directly use the parent class code.
 Method Overriding: Method Overriding is achievable only through
Inheritance. It is one of the ways by which Java achieves Run Time
Polymorphism.
 Abstraction: The concept of abstract where we do not have to provide all
details is achieved through inheritance. Abstraction only shows the
functionality to the user.
Important Terminologies Used in Java Inheritance
 Class: Class is a set of objects which shares common characteristics/
behavior and common properties/ attributes. Class is not a real-world
entity. It is just a template or blueprint or prototype from which objects are
created.
 Super Class/Parent Class: The class whose features are inherited is
known as a superclass(or a base class or a parent class).
 Sub Class/Child Class: The class that inherits the other class is known as
a subclass(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 extends keyword is used for inheritance in Java. Using the extends keyword
indicates you are derived from an existing class. In other words, “extends” refers to
increased functionality.
Syntax :
class derived-class extends base-class
{
//methods and fields
}
In the below example of inheritance, class Employee is a base class, class Engineer
is a derived class that extends the Employee class and class Test is a driver class to
run the program.
 Java
// Java Program to illustrate Inheritance (concise)

import java.io.*;

// Base or Super Class

class Employee {

int salary = 60000;

// Inherited or Sub Class

class Engineer extends Employee {

int benefits = 10000;

// Driver Class

class Gfg {

public static void main(String args[])

Engineer E1 = new Engineer();

System.out.println("Salary : " + E1.salary

+ "\nBenefits : " + E1.benefits);

Output
Salary : 60000
Benefits : 10000
In practice, inheritance, and polymorphism are used together in Java to achieve fast
performance and readability of code.
Java Inheritance Types
Below are the different types of inheritance which are supported by Java.
1. Single Inheritance
2. Multilevel Inheritance
3. Hierarchical Inheritance
4. Multiple Inheritance
5. Hybrid Inheritance
1. Single Inheritance
In single inheritance, subclasses inherit the features of one superclass. In the image
below, class A serves as a base class for the derived class B.

// Java program to illustrate the


// concept of single inheritance
import java.io.*;
import java.lang.*;
import java.util.*;

// Parent class
class one {
public void print_geek()
{
System.out.println("Geeks");
}
}

class two extends one {


public void print_for() { System.out.println("for"); }
}

// Driver class
public class Main {
// Main function
public static void main(String[] args)
{
two g = new two();
g.print_geek();
g.print_for();
g.print_geek();
}
}

. Multilevel Inheritance
In Multilevel Inheritance, a derived class will be inheriting a base class, and as well
as the derived class also acts as the base class for other classes. In the below image,
class A serves as a base class for the derived class B, which in turn serves as a base
class for the derived class C. In Java, a class cannot directly access the grandparent’s
members.

import java.io.*;
import java.lang.*;
import java.util.*;

class one {
public void print_geek()
{
System.out.println("Geeks");
}
}

class two extends one {


public void print_for() { System.out.println("for"); }
}

class three extends two {


public void print_geek()
{
System.out.println("Geeks");
}
}

// Drived class
public class Main {
public static void main(String[] args)
{
three g = new three();
g.print_geek();
g.print_for();
g.print_geek();
}
}

. Hierarchical Inheritance
In Hierarchical Inheritance, one class serves as a superclass (base class) for more
than one subclass. In the below image, class A serves as a base class for the derived
classes B, C, and D.

Multiple Inheritance (Through Interfaces)


In Multiple inheritances , one class can have more than one superclass and inherit
features from all parent classes. Please note that Java does not support multiple
inheritances with classes. In Java, we can achieve multiple inheritances only
through Interfaces. In the image below, Class C is derived from interfaces A and B.
Multiple Inheritance

 Java
// Java program to illustrate the

// concept of Multiple inheritance

import java.io.*;

import java.lang.*;

import java.util.*;

interface one {

public void print_geek();

interface two {

public void print_for();

interface three extends one, two {

public void print_geek();

class child implements three {

@Override public void print_geek()

System.out.println("Geeks");

public void print_for() { System.out.println("for"); }

}
// Drived class

public class Main {

public static void main(String[] args)

child c = new child();

c.print_geek();

c.print_for();

c.print_geek();

5. Hybrid Inheritance
It is a mix of two or more of the above types of inheritance. Since Java doesn’t
support multiple inheritances with classes, hybrid inheritance involving multiple
inheritance is also not possible with classes. In Java, we can achieve hybrid
inheritance only through Interfaces if we want to involve multiple inheritance to
implement Hybrid inheritance.
However, it is important to note that Hybrid inheritance does not necessarily require
the use of Multiple Inheritance exclusively. It can be achieved through a
combination of Multilevel Inheritance and Hierarchical Inheritance with classes,
Hierarchical and Single Inheritance with classes. Therefore, it is indeed possible to
implement Hybrid inheritance using classes alone, without relying on multiple
inheritance type.

Advantages Of Inheritance in Java:


1. Code Reusability: Inheritance allows for code reuse and reduces the
amount of code that needs to be written. The subclass can reuse the
properties and methods of the superclass, reducing duplication of code.
2. Abstraction: Inheritance allows for the creation of abstract classes that
define a common interface for a group of related classes. This promotes
abstraction and encapsulation, making the code easier to maintain and
extend.
3. Class Hierarchy: Inheritance allows for the creation of a class hierarchy,
which can be used to model real-world objects and their relationships.
4. Polymorphism: Inheritance allows for polymorphism, which is the ability
of an object to take on multiple forms. Subclasses can override the
methods of the superclass, which allows them to change their behavior in
different ways.
Disadvantages of Inheritance in Java:
1. Complexity: Inheritance can make the code more complex and harder to
understand. This is especially true if the inheritance hierarchy is deep or if
multiple inheritances is used.
2. Tight Coupling: Inheritance creates a tight coupling between the
superclass and subclass, making it difficult to make changes to the
superclass without affecting the subclass.

Java Constructors


Java constructors or constructors in Java is a terminology used to construct something
in our programs. A constructor in Java is a special method that is used to initialize
objects. The constructor is called when an object of a class is created. It can be used to
set initial values for object attributes.
What are Constructors in Java?
In Java, Constructor is a block of codes similar to the method. It is called when an
instance of the class is created. At the time of calling the constructor, memory for the
object is allocated in the memory. It is a special type of method that is used to
initialize the object. Every time an object is created using the new() keyword, at least
one constructor is called.
// Java Program to demonstrate
// Constructor
import java.io.*;

class Geeks {
// Constructor
Geeks()
{
super();
System.out.println("Constructor Called");
}

// main function
public static void main(String[] args)
{
Geeks geek = new Geeks();
}
}
How Java Constructors are Different From Java Methods?
Constructors must have the same name as the class within which it is

defined it is not necessary for the method in Java.
 Constructors do not return any type while method(s) have the return type
or void if does not return any value.
 Constructors are called only once at the time of Object creation while
method(s) can be called any number of times.
Now let us come up with the syntax for the constructor being invoked at the time of
object or instance creation.
class Geek
{
.......

// A Constructor
Geek() {
}

.......
}
Geek obj = new Geek();
The first line of a constructor is a call to super() or this(), (a call to a constructor of a
super-class or an overloaded constructor), if you don’t type in the call to super in
your constructor the compiler will provide you with a non-argument call to super at
the first line of your code, the super constructor must be called to create an object:

Need of Constructors in Java


Think of a Box. If we talk about a bo x class then it will have some class variables
(say length, breadth, and height). But when it comes to creating its object(i.e Box
will now exist in the computer’s memory), then can a box be there with no value
defined for its dimensions? The answer is No.
So constructors are used to assign values to the class variables at the time of object
creation, either explicitly done by the programmer or by Java itself (default
constructor).
When Constructor is called?
Each time an object is created using a new() keyword, at least one constructor (it
could be the default constructor) is invoked to assign initial values to the data
members of the same class. Rules for writing constructors are as follows:
 The constructor(s) of a class must have the same name as the class name
in which it resides.
 A constructor in Java can not be abstract, final, static, or Synchronized.
 Access modifiers can be used in constructor declaration to control its
access i.e which other class can call the constructor.
So by far, we have learned constructors are used to initialize the object’s state.
Like methods, a constructor also contains a collection of statements(i.e. instructions)
that are executed at the time of Object creation.
Types of Constructors in Java
Now is the correct time to discuss the types of the constructor, so primarily there are
three types of constructors in Java are mentioned below:
 Default Constructor
 Parameterized Constructor
 Copy Constructor
1. Default Constructor in Java
A constructor that has no parameters is known as default the constructor. A default
constructor is invisible. And if we write a constructor with no arguments, the
compiler does not create a default constructor. It is taken out. It is being overloaded
and called a parameterized constructor. The default constructor changed into the
parameterized constructor. But Parameterized constructor can’t change the default
constructor.

You might also like