0% found this document useful (0 votes)
4 views23 pages

Module 3.Docx

Java inheritance is a core concept of Object-Oriented Programming that allows one class to inherit fields and methods from another, promoting code reusability and abstraction. It includes various types such as single, multilevel, hierarchical, multiple (through interfaces), and hybrid inheritance. Inheritance enables subclasses to extend or override superclass functionality, facilitating a structured class hierarchy and polymorphism.

Uploaded by

sukunansr
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
4 views23 pages

Module 3.Docx

Java inheritance is a core concept of Object-Oriented Programming that allows one class to inherit fields and methods from another, promoting code reusability and abstraction. It includes various types such as single, multilevel, hierarchical, multiple (through interfaces), and hybrid inheritance. Inheritance enables subclasses to extend or override superclass functionality, facilitating a structured class hierarchy and polymorphism.

Uploaded by

sukunansr
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 23

Java Inheritance

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 DerivedClass extends BaseClass { //methods and fields }

Inheritance in Java Example


Example: In the below example of inheritance, class Bicycle is a base class, class
MountainBike is a derived class that extends the Bicycle class and class Test is a driver class
to run the program.
Java// Java program to illustrate the // concept of inheritance // base class class Bicycle { //
the Bicycle class has two fields public int gear; public int speed; // the Bicycle class has one
constructor public Bicycle(int gear, int speed) { this.gear = gear; this.speed = speed; } // the
Bicycle class has three methods public void applyBrake(int decrement) { speed -= decrement;
} public void speedUp(int increment) { speed += increment; } // toString() method to print
info of Bicycle public String toString() { return ("No of gears are " + gear + "\n" + "speed of
bicycle is " + speed); } } // derived class class MountainBike extends Bicycle { // the
MountainBike subclass adds one more field public int seatHeight; // the MountainBike
subclass has one constructor public MountainBike(int gear, int speed, int startHeight) { //
invoking base-class(Bicycle) constructor super(gear, speed); seatHeight = startHeight; } // the
MountainBike subclass adds one more method public void setHeight(int newValue) {
seatHeight = newValue; } // overriding toString() method // of Bicycle to print more info
@Override public String toString() { return (super.toString() + "\nseat height is " +
seatHeight); } } // driver class public class Test { public static void main(String args[]) {
MountainBike mb = new MountainBike(3, 100, 25); System.out.println(mb.toString()); } }

Output

No of gears are 3 speed of bicycle is 100 seat height is 25

In the above program, when an object of MountainBike class is created, a copy of all methods
and fields of the superclass acquires memory in this object. That is why by using the object of
the subclass we can also access the members of a superclass.

Please note that during inheritance only the object of the subclass is created, not the
superclass. For more, refer to Java Object Creation of Inherited Class.

Example 2: 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

Illustrative image of the program:


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, a sub-class is derived from only one super class. It inherits the
properties and behavior of a single-parent class. Sometimes, it is also known as simple
inheritance. In the below figure, ‘A’ is a parent class and ‘B’ is a child class. The class ‘B’
inherits all the properties of the class ‘A’.
Single inheritance

Java// 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(); }
}

Output

Geeks for Geeks

2. 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.
Multilevel Inheritance

Java` // Importing required libraries import java.io.; import java.lang.; import java.util.*; //
Parent class One class One { // Method to print "Geeks" public void print_geek() {
System.out.println("Geeks"); } } // Child class Two inherits from class One class Two
extends One { // Method to print "for" public void print_for() { System.out.println("for"); } }
// Child class Three inherits from class Two class Three extends Two { // Method to print
"Geeks" public void print_lastgeek() { System.out.println("Geeks"); } } // Driver class public
class Main { public static void main(String[] args) { // Creating an object of class Three
Three g = new Three();

// Calling method from class One g.print_geek(); // Calling method from class Two
g.print_for(); // Calling method from class Three g.print_lastgeek(); }

}`

Output

Geeks for Geeks

3. 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.
Java// Java program to illustrate the // concept of Hierarchical inheritance class A { public
void print_A() { System.out.println("Class A"); } } class B extends A { public void print_B()
{ System.out.println("Class B"); } } class C extends A { public void print_C() {
System.out.println("Class C"); } } class D extends A { public void print_D() {
System.out.println("Class D"); } } // Driver Class public class Test { public static void
main(String[] args) { B obj_B = new B(); obj_B.print_A(); obj_B.print_B(); C obj_C = new
C(); obj_C.print_A(); obj_C.print_C(); D obj_D = new D(); obj_D.print_A();
obj_D.print_D(); } }

Output

Class A Class B Class A Class C Class A Class D

4. 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(); } }

Output

Geeks for Geeks

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.
Hybrid Inheritance

Java IS-A type of Relationship


IS-A is a way of saying: This object is a type of that object. Let us see how the extends
keyword is used to achieve inheritance.

Javapublic class SolarSystem { } public class Earth extends SolarSystem { } public class
Mars extends SolarSystem { } public class Moon extends Earth { }

Now, based on the above example, in Object-Oriented terms, the following are true:-

●​ SolarSystem is the superclass of Earth class.


●​ SolarSystem is the superclass of Mars class.
●​ Earth and Mars are subclasses of SolarSystem class.
●​ Moon is the subclass of both Earth and SolarSystem classes.

Javaclass SolarSystem { } class Earth extends SolarSystem { } class Mars extends


SolarSystem { } public class Moon extends Earth { public static void main(String args[]) {
SolarSystem s = new SolarSystem(); Earth e = new Earth(); Mars m = new Mars();
System.out.println(s instanceof SolarSystem); System.out.println(e instanceof Earth);
System.out.println(m instanceof SolarSystem); } }Try it on GfG Practice \ \

Output

true true true


What Can Be Done in a Subclass?
In sub-classes we can inherit members as is, replace them, hide them, or supplement them
with new members:

●​ The inherited fields can be used directly, just like any other fields.
●​ We can declare new fields in the subclass that are not in the superclass.
●​ The inherited methods can be used directly as they are.
●​ We can write a new instance method in the subclass that has the same signature as the
one in the superclass, thus overriding it (as in the example above, toString() method is
overridden).
●​ We can write a new static method in the subclass that has the same signature as the
one in the superclass, thus hiding it.
●​ We can declare new methods in the subclass that are not in the superclass.
●​ We can write a subclass constructor that invokes the constructor of the superclass,
either implicitly or by using the keyword super.

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.

Conclusion
Let us check some important points from the article are mentioned below:

●​ Default superclass: Except Object class, which has no superclass, every class has one
and only one direct superclass (single inheritance). In the absence of any other explicit
superclass, every class is implicitly a subclass of the Object class.
●​ Superclass can only be one: A superclass can have any number of subclasses. But a
subclass can have only one superclass. This is because Java does not support multiple
inheritances with classes. Although with interfaces, multiple inheritances are
supported by Java.
●​ Inheriting Constructors: A subclass inherits all the members (fields, methods, and
nested classes) from its superclass. Constructors are not members, so they are not
inherited by subclasses, but the constructor of the superclass can be invoked from the
subclass.
●​ Private member inheritance: A subclass does not inherit the private members of its
parent class. However, if the superclass has public or protected methods(like getters
and setters) for accessing its private fields, these can also be used by the subclass.

FAQs in Inheritance
1. What is Inheritance Java?

Inheritance is a concept of OOPs where one class inherits from another class that can reuse
the methods and fields of the parent class.

2. What are the 4 types of inheritance in Java?

There are Single, Multiple, Multilevel, Hierarchical and Hybrid

3. What is the use of extend keyword?

Extend keyword is used for inheriting one class into another.

4. What is an example of inheritance in Java?

A real-world example of Inheritance in Java is mentioned below:

Consider a group of vehicles. You need to create classes for Bus, Car, and Truck. The
methods fuelAmount(), capacity(), applyBrakes() will be the same for all three classes.

Polymorphism
The word ‘ polymorphism’ means ‘ having many forms’. In Java, polymorphism refers to
the ability of a message to be displayed in more than one form. This concept is a key feature
of Object-Oriented Programming and it allows objects to behave differently based on their
specific class type.
Real-life Illustration of Polymorphism in Java: A person can have different characteristics
at the same time. Like a man at the same time is a father, a husband, and an employee. So the
same person possesses different behaviors in different situations. This is called
polymorphism.
Example: A Person Having Different Roles
Java` // Base class Person class Person {
// Method that displays the // role of a person void role() { System.out.println("I am a
person."); }
} // Derived class Father that // overrides the role method class Father extends Person {
// Overridden method to show // the role of a father @Override void role() {
System.out.println("I am a father."); }
} public class Main { public static void main(String[] args) {
// Creating a reference of type Person // but initializing it with Father class object Person p =
new Father(); // Calling the role method. It calls the // overridden version in Father class
p.role(); }
}`
Output
I am a father.
Explanation: In the above example, the Person class has a method role() that prints a
general message. The Father class overrides role() to print a specific message. The
reference of type Person is used to point to an object of type Father, demonstrating
polymorphism at runtime. The overridden method in Father is invoked when role() is called.

Types of Java Polymorphism


In Java Polymorphism is mainly divided into two types:

●​ Compile-Time Polymorphism
●​ Runtime Polymorphism
1. Compile-Time Polymorphism
Compile-Time Polymorphism in Java is also known as static polymorphism. This type of
polymorphism is achieved by function overloading or operator overloading.
Note: But Java doesn’t support the Operator Overloading.
Method Overloading
Method overloading in Java means when there are multiple functions with the same name but
different parameters then these functions are said to be overloaded. Functions can be
overloaded by changes in the number of arguments or/and a change in the type of arguments.
Example: Method overloading by changing the number of arguments
Java` // Method overloading By using // Different Types of Arguments // Class 1 // Helper
class class Helper { // Method with 2 integer parameters static int Multiply(int a, int b) { //
Returns product of integer numbers return a * b; } // Method 2 // With same name but with 2
double parameters static double Multiply(double a, double b) { // Returns product of double
numbers return a * b; } } // Class 2 // Main class class Geeks { // Main driver method public
static void main(String[] args) {
// Calling method by passing // input as in arguments System.out.println(Helper.Multiply(2,
4)); System.out.println(Helper.Multiply(5.5, 6.3)); }
}`
Output
8 34.65
Subtypes of Compile-time Polymorphism:
●​ Function Overloading: It is a feature in C++/Java where multiple functions can have the same
name but with different parameter lists. The compiler will decide which function to call
based on the number and types of arguments passed to the function.
●​ Operator Overloading: It is a feature in C++ where the operators such as +, -, *, etc. can be
given additional meanings when applied to user-defined data types.
●​ Template: It is a powerful feature in C++ that allows us to write generic functions and classes.
A template is a blueprint for creating a family of functions or classes.

2. Runtime Polymorphism
Runtime Polymorphism in Java known as Dynamic Method Dispatch. It is a process in which
a function call to the overridden method is resolved at Runtime. This type of polymorphism is
achieved by Method Overriding. Method overriding, on the other hand, occurs when a
derived class has a definition for one of the member functions of the base class. That base
function is said to be overridden.
Method Overriding
Java// Java Program for Method Overriding // Class 1 // Helper class class Parent { // Method
of parent class void Print() { System.out.println("parent class"); } } // Class 2 // Helper class
class subclass1 extends Parent { // Method void Print() { System.out.println("subclass1"); } }
// Class 3 // Helper class class subclass2 extends Parent { // Method void Print() {
System.out.println("subclass2"); } } // Class 4 // Main class class Geeks { // Main driver
method public static void main(String[] args) { // Creating object of class 1 Parent a; // Now
we will be calling print methods // inside main() method a = new subclass1(); a.Print(); a =
new subclass2(); a.Print(); } }
Output
subclass1 subclass2
Explanation: In the above example, when an object of a child class is created, then the
method inside the child class is called. This is because the method in the parent class is
overridden by the child class. Since the method is overridden, This method has more priority
than the parent method inside the child class. So, the body inside the child class is executed.
Subtype of Run-Time Polymorphism
Virtual Functions: It allows an object of a derived class to behave as if it were an object of
the base class. The derived class can override the virtual function of the base class to provide
its own implementation. The function call is resolved at runtime, depending on the actual
type of the object.

Advantages of Polymorphism

●​ Increases code reusability by allowing objects of different classes to be treated as objects of


a common class.
●​ Improves readability and maintainability of code by reducing the amount of code that needs
to be written and maintained.
●​ Supports dynamic binding, enabling the correct method to be called at runtime, based on
the actual class of the object.
●​ Enables objects to be treated as a single type, making it easier to write generic code that can
handle objects of different types.
Disadvantages of Polymorphism

●​ Can make it more difficult to understand the behavior of an object, especially if the code is
complex.
●​ This may lead to performance issues, as polymorphic behavior may require additional
computations at runtime.

Difference Between Method Overloading and Method


Overriding in Java
The differences between Method Overloading and Method Overriding in Java are as follows:
Method Overloading Method Overriding Method overloading is a compile-time
polymorphism. Method overriding is a run-time polymorphism. Method overloading helps to
increase the readability of the program. Method overriding is used to grant the specific
implementation of the method which is already provided by its parent class or superclass. It
occurs within the class. It is performed in two classes with inheritance relationships. Method
overloading may or may not require inheritance. Method overriding always needs
inheritance. In method overloading, methods must have the same name and different
signatures. In method overriding, methods must have the same name and same signature. In
method overloading, the return type can or can not be the same, but we just have to change
the parameter. In method overriding, the return type must be the same or co-variant. Static
binding is being used for overloaded methods. Dynamic binding is being used for overriding
methods. Private and final methods can be overloaded. Private and final methods can’t be
overridden. The argument list should be different while doing method overloading. The
argument list should be the same in method overriding.

Method Overloading in Java


Method Overloading is a Compile time polymorphism. In method overloading, more than
one method shares the same method name with a different signature in the class. In method
overloading, the return type can or can not be the same, but we have to change the parameter
because, in java, we can not achieve method overloading by changing only the return type of
the method.
Example of Method Overloading:
Java// Java Program to Implement // Method Overloading import java.io.*; class
MethodOverloadingEx { static int add(int a, int b) { return a + b; } static int add(int a, int b,
int c) { return a + b + c; } // Main Function public static void main(String args[]) {
System.out.println("add() with 2 parameters"); // Calling function with 2 parameters
System.out.println(add(4, 6)); System.out.println("add() with 3 parameters"); // Calling
function with 3 Parameters System.out.println(add(4, 6, 7)); } }
Output
add() with 2 parameters 10 add() with 3 parameters 17

Method Overriding in Java


Method Overriding is a type of runtime polymorphism. In method overriding, a method in a
derived class has the same name, return type, and parameters as a method in its parent class.
The derived class provides a specific implementation for the method that is already defined in
the parent class.
Example of Method Overriding:
Java` import java.io.*; // Base Class class Animal { void eat() { System.out.println("eat()
method of base class"); System.out.println("Animal is eating."); } } // Derived Class class
Dog extends Animal { @Override void eat() { System.out.println("eat() method of derived
class"); System.out.println("Dog is eating."); }
// Method to call the base class method void eatAsAnimal() { super.eat(); }
} // Driver Class class MethodOverridingEx { // Main Function public static void main(String
args[]) { Dog d1 = new Dog(); Animal a1 = new Animal(); // Calls the eat() method of Dog
class d1.eat(); // Calls the eat() method of Animal class a1.eat(); // Polymorphism: Animal
reference pointing to Dog object Animal animal = new Dog();
// Calls the eat() method of Dog class animal.eat(); // To call the base class method, you need
to use a Dog reference ((Dog) animal).eatAsAnimal(); }
}`
Output
eat() method of derived class Dog is eating. eat() method of base class Animal is eating. eat()
method of derived class Dog is eating. eat() method of base class Animal is eating.
Explanation of the above Program:
Here, we can see that a method eat() has overridden in the derived class name Dog that is
already provided by the base class name Animal. When we create the instance of class Dog
and call the eat() method, we see that only derived class eat() method run instead of base
class method eat(), and When we create the instance of class Animal and call the eat()
method, we see that only base class eat() method run instead of derived class method eat().

The differences between Method Overloading and Method Overriding in


Java are as follows:
Method Overloading Method Overriding

Method overloading is a Method overriding is a run-time


compile-time polymorphism. polymorphism.
Method Overloading Method Overriding

Method overriding is used to grant the


Method overloading helps to
specific implementation of the method
increase the readability of the
which is already provided by its parent
program.
class or superclass.

It is performed in two classes with


It occurs within the class.
inheritance relationships.

Method overloading may or may Method overriding always needs


not require inheritance. inheritance.

In method overloading, methods


In method overriding, methods must have
must have the same name and
the same name and same signature.
different signatures.

In method overloading, the return


type can or cannot be the same, In method overriding, the return type must
but we just have to change the be the same or co-variant.
parameter.

Static binding is being used for Dynamic binding is being used for
overloaded methods. overriding methods.

Private and final methods can be Private and final methods can’t be
overloaded. overridden.

The argument list should be


The argument list should be the same in
different while doing method
method overriding.
overloading.

An Interface in Java programming language is defined as an abstract type used to specify


the behavior of a class. An interface in Java is a blueprint of a behavior. A Java interface
contains static constants and abstract methods.

●​ The interface in Java is a mechanism to achieve abstraction.


●​ By default, variables in an interface are public, static, and final.
●​ It is used to achieve abstraction and multiple inheritances in Java.
●​ It is also used to achieve loose coupling.
●​ In other words, interfaces primarily define methods that other classes must implement.
●​ An interface in Java defines a set of behaviors that a class can implement, usually
representing an IS-A relationship, but not always in every scenario.

Example:
Java` {...} //Driver Code Starts{ import java.io.*; // Interface Declared //Driver Code Ends }
interface testInterface {
// public, static and final final int a = 10; // public and abstract void display();
} // Class implementing interface class TestClass implements testInterface {
// Implementing the capabilities of // Interface public void display(){
System.out.println("Geek"); }
} class Geeks {...} //Driver Code Starts{ { public static void main(String[] args) { TestClass t
= new TestClass(); t.display(); System.out.println(t.a); } } //Driver Code Ends } `
Output
Geek 10
Note: In Java, the abstract keyword applies only to classes and methods, indicating that they
cannot be instantiated directly and must be implemented. When we decide on a type of entity
by its behaviour and not via attribute we should define it as an interface.

Syntax
interface {
// declare constant fields
// declare methods that abstract
// by default.
}
To declare an interface, use the interface keyword. It is used to provide total abstraction. That
means all the methods in an interface are declared with an empty body and are public and all
fields are public, static, and final by default. A class that implements an interface must
implement all the methods declared in the interface. To implement the interface, use the
implements keyword.

Relationship Between Class and Interface


A class can extend another class, and similarly, an interface can extend another interface.
However, only a class can implement an interface, and the reverse (an interface implementing
a class) is not allowed.
Difference Between Class and Interface
Although Class and Interface seem the same there are certain differences between Classes
and Interface. The major differences between a class and an interface are mentioned below:
Class Interface In class, you can instantiate variables and create an object. In an interface, you
must initialize variables as they are final but you can’t create an object. A class can contain
concrete (with implementation) methods The interface cannot contain concrete (with
implementation) methods. The access specifiers used with classes are private, protected, and
public. In Interface only one specifier is used- Public.
Implementation: To implement an interface, we use the keyword implements
Let’s consider the example of Vehicles like bicycles, cars, and bikes share common
functionalities, which can be defined in an interface, allowing each class (e.g., Bicycle, Car,
Bike) to implement them in its own way. This approach ensures code reusability, scalability,
and consistency across different vehicle types.
Example:
Java` import java.io.*; interface Vehicle {
// Abstract methods defined void changeGear(int a); void speedUp(int a); void
applyBrakes(int a);
} // Class implementing vehicle interface class Bicycle implements Vehicle{
int speed; int gear; // Change gear @Override public void changeGear(int newGear){ gear =
newGear; } // Increase speed @Override public void speedUp(int increment){ speed = speed
+ increment; } // Decrease speed @Override public void applyBrakes(int decrement){ speed
= speed - decrement; } public void printStates() { System.out.println("speed: " + speed + "
gear: " + gear); }
} // Class implementing vehicle interface class Bike implements Vehicle {
int speed; int gear; // Change gear @Override public void changeGear(int newGear){ gear =
newGear; } // Increase speed @Override public void speedUp(int increment){ speed = speed
+ increment; } // Decrease speed @Override public void applyBrakes(int decrement){ speed
= speed - decrement; } public void printStates() { System.out.println("speed: " + speed + "
gear: " + gear); }
} class Main { public static void main (String[] args) {
// Instance of Bicycle(Object) Bicycle bicycle = new Bicycle(); bicycle.changeGear(2);
bicycle.speedUp(3); bicycle.applyBrakes(1); System.out.print("Bicycle present state : ");
bicycle.printStates(); // Instance of Bike (Object) Bike bike = new Bike();
bike.changeGear(1); bike.speedUp(4); bike.applyBrakes(3); System.out.print("Bike present
state : "); bike.printStates(); }
}`
Output
Bicycle present state : speed: 2 gear: 2 Bike present state : speed: 1 gear: 1
Multiple Inheritance in Java Using Interface
Multiple Inheritance is an OOPs concept that can’t be implemented in Java using classes. But
we can use multiple inheritances in Java using Interface. Let us check this with an example.

Example:
Java` import java.io.*; // Add interface interface Add{ int add(int a,int b); } // Sub interface
interface Sub{ int sub(int a,int b); } // Calculator class implementing // Add and Sub class Cal
implements Add , Sub { // Method to add two numbers public int add(int a,int b){ return a+b;
}
// Method to sub two numbers public int sub(int a,int b){ return a-b; }
} class GFG{ // Main Method public static void main (String[] args) { // instance of Cal class
Cal x = new Cal();
System.out.println("Addition : " + x.add(2,1)); System.out.println("Substraction : " +
x.sub(2,1)); }
}`
Output
Addition : 3 Substraction : 1

New Features Added in Interfaces in JDK 8


There are certain features added to Interfaces in JDK 8 update mentioned below:
1. Default Methods

●​ Interfaces can define methods with default implementations.


●​ Useful for adding new methods to interfaces without breaking existing implementations.

Java` // interfaces can have methods from JDK 1.8 onwards interface TestInterface { final int
a = 10;
default void display() { System.out.println("hello"); }
} // A class that implements the interface. class TestClass implements TestInterface { //
Driver Code public static void main (String[] args) { TestClass t = new TestClass();
t.display(); } } `
Output
hello
2. Static Methods

●​ Interfaces can now include static methods.


●​ These methods are called directly using the interface name and are not inherited by
implementing classes.

Another feature that was added in JDK 8 is that we can now define static methods in
interfaces that can be called independently without an object. These methods are not
inherited.
Javainterface TestInterface { final int a = 10; static void display() {
System.out.println("hello"); } } // A class that implements the interface. class TestClass
implements TestInterface { // Driver Code public static void main (String[] args) {
TestInterface.display(); } }
Output
hello

Extending Interfaces
One interface can inherit another by the use of keyword extends. When a class implements an
interface that inherits another interface, it must provide an implementation for all methods
required by the interface inheritance chain.
Java` interface A { void method1(); void method2(); } // B now includes method1 // and
method2 interface B extends A { void method3(); } // the class must implement // all method
of A and B. class GFG implements B { public void method1() { System.out.println("Method
1"); }
public void method2() { System.out.println("Method 2"); } public void method3() {
System.out.println("Method 3"); } public static void main(String[] args){ // Instance of GFG
class created GFG x = new GFG(); // All Methods Called x.method1(); x.method2();
x.method3(); }
}`
Output
Method 1 Method 2 Method 3
In a Simple way, the interface contains multiple abstract methods, so write the
implementation in implementation classes. If the implementation is unable to provide an
implementation of all abstract methods, then declare the implementation class with an
abstract modifier, and complete the remaining method implementation in the next created
child classes. It is possible to declare multiple child classes but at final we have completed
the implementation of all abstract methods.
In general, the development process is step by step:
Level 1 – interfaces: It contains the service details.
Level 2 – abstract classes: It contains partial implementation.
Level 3 – implementation classes: It contains all implementations.
Level 4 – Final Code / Main Method: It have access of all interfaces data.
Example:
Java// implementation Level wise import java.io.*; import java.lang.*; import java.util.*; //
Level 1 interface Bank { void deposit(); void withdraw(); void loan(); void account(); } //
Level 2 abstract class Dev1 implements Bank { public void deposit() {
System.out.println("Your deposit Amount :" + 100); } } abstract class Dev2 extends Dev1 {
public void withdraw() { System.out.println("Your withdraw Amount :" + 50); } } // Level 3
class Dev3 extends Dev2 { public void loan() {} public void account() {} } // Level 4 class
Main { public static void main(String[] args) { Dev3 d = new Dev3(); d.account(); d.loan();
d.deposit(); d.withdraw(); } }Try it on GfG Practice \ \

Output
Your deposit Amount :100 Your withdraw Amount :50

Advantages of Interfaces
●​ Without bothering about the implementation part, we can achieve the security of the
implementation.
●​ In Java, multiple inheritances are not allowed, however, you can use an interface to make use
of it as you can implement more than one interface.

New Features Added in Interfaces in JDK 9


From Java 9 onwards, interfaces can contain the following also:

1.​ Static methods


2.​ Private methods
3.​ Private Static methods

Important Points
In the article, we learn certain important points about interfaces as mentioned below:

●​ We can’t create an instance (interface can’t be instantiated) of the interface but we can make
the reference of it that refers to the Object of its implementing class.
●​ A class can implement more than one interface.
●​ An interface can extend to another interface or interface (more than one interface).
●​ A class that implements the interface must implement all the methods in the interface.
●​ All the methods are public and abstract. All the fields are public, static, and final.
●​ It is used to achieve multiple inheritances.
●​ It is used to achieve loose coupling.
●​ Inside the Interface not possible to declare instance variables because by default variables
are public static final.
●​ Inside the Interface, constructors are not allowed.
●​ Inside the interface main method is not allowed.
●​ Inside the interface, static, final, and private methods declaration are not possible.
FAQs
1. What is a marker or tagged interface?
Tagged Interfaces are interfaces without any methods they serve as a marker without any
capabilities.

2. How many Types of interfaces in Java?


Types of interfaces in Java are mentioned below:

1.​ Functional Interface


2.​ Marker interface

3. Why multiple inheritance is not supported through class in Java?


Multiple Inheritance is not supported through class in Java so to avoid certain challenges like
Ambiguity and diamond problems.

4. Why use interfaces when we have abstract classes?


The reason is, that abstract classes may contain non-final variables, whereas variables in the
interface are final, public, and static.
// A simple interface
interface Player {
final int id = 10;
int move();
}

You might also like