0% found this document useful (0 votes)
0 views

Interface in Java with Examples

This document provides a comprehensive overview of interfaces in Java, explaining their purpose, structure, and rules for implementation. It highlights the differences between interfaces and classes, the need for interfaces to support multiple inheritance, and includes examples to illustrate their usage. Key points include that interfaces cannot be instantiated, contain only abstract methods, and can be implemented by multiple classes.
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
0 views

Interface in Java with Examples

This document provides a comprehensive overview of interfaces in Java, explaining their purpose, structure, and rules for implementation. It highlights the differences between interfaces and classes, the need for interfaces to support multiple inheritance, and includes examples to illustrate their usage. Key points include that interfaces cannot be instantiated, contain only abstract methods, and can be implemented by multiple classes.
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 12

Interface in Java with Examples

In this article, I am going to discuss Interface in Java . At the end of this


article, you will understand what an Interface in Java is and its need, as
well as when and how to use the Interfaces in Java with Examples.

Interface
Java interface is a collection of abstract methods. The interface is used to
achieve abstraction in which you can define methods without their
implementations (without having the body of the methods).
• An interface is a reference type and is similar to the class.
• Along with abstract methods, an interface may also contain
constants, default methods, static methods, and nested types.
• Method bodies exist only for default methods and static methods.
• Writing an interface is similar to writing a class.
• However, a class describes the attributes and behaviors of an object.
• An interface contains behaviors that a class implements.
• Unless the class that implements the interface is abstract, all the
methods of the interface need to be defined in the class.

Java Interfaces and Classes: Similarities and Differences and Similarities


An interface is similar to a class in the following ways −
• An interface can contain any number of methods.
• An interface is written in a file with a .java extension, with the
name of the interface matching the name of the file.
• The byte code of an interface appears in a .class file.
• Interfaces appear in packages, and their corresponding
bytecode file must be in a directory structure that matches the
package name.

Differences
However, an interface is different from a class in several ways, including :
• You cannot instantiate an interface.
• An interface does not contain any constructors.
• All of the methods in an interface are abstract.
• An interface cannot contain instance fields. The only fields that
can appear in an interface must be declared both static and
final.
• An interface is not extended by a class; it is implemented by a
class.
• An interface can extend multiple interfaces.
Why do we need Interfaces in java?
We know the concept of multiple inheritances where one class is derived
from more than one superclass. For example a definition like the below.

But this concept is not supported by java with classes.


Since a large no of real-time applications are required for the use of
multiple inheritances where we inherit properties from several different
classes.
That’s why java provides an alternative approach known as the interface
to support the concept of multiple Inheritance.

Note: It can be used to achieve loose coupling.


• Since methods in interfaces do not have a body, they have to be
implemented by the class before you can access them.
• The class that implements an interface must implement all the
methods of that interface.

What is an interface in Java?


• The interface is a fully un-implemented class used for declaring a set
of operations of an object.
• So, you can consider it is a pure abstract class that allows you to
define only public static final variables and public abstract methods.
• In our previous article, we already discussed that abstract method
means method without body or implementation.
Now, you may have the following question in your mind.

What is the need for the interface when we already have abstract
classes to define abstract methods?
Java doesn’t support multiple inheritances with classes. So we must use
the interface as a superclass to develop abstraction for supporting
multiple inheritances.

If we define an abstract class in place of an interface, a service provider


cannot implement multiple specifications so the service providers cannot
have multiple businesses.

If this is not clear at the moment, then don’t worry we will discuss this in
detail with an example.

How to declare an interface in Java?


By using the keyword interface you can declare a class type of interface.
The syntax is given below.

An example is given below.

Here the keyword interface tells that Example is an interface containing


two final fields such as x and name and one abstract method such as
show().

By default, the members of an interface are abstract and final means


abstract methods and final fields. Save the above interface in a file
Example.java. We can compile the interface but we cannot execute it
because it does not have the main method.

When a class implements an interface, you can think of the class as


signing a contract, agreeing to perform the specific behaviors of the
interface.
If a class does not perform all the behaviors of the interface, the class
must declare itself as abstract.

A class uses the implements keyword to implement an interface.


The implements keyword appears in the class declaration following the
extends portion of the declaration.

Let us check what happens when we compile and execute it

Javac Example.java
Example.class

Java Example
Exception in thread “main” java.lang.NoSuchMethodError: main
Interface Example in Java:
Let us see an example to understand how the interface is used in the java
application.

Let us first create an interface with the name Shape and then copy and
paste the following code into it.

interface Shape
{
public double Area();
public double Volume();
}

As you can see, here, we created the interface with two methods (Area
and Volume).
Now we will create two classes (Cube and Circle) and then we will
implement the Shape interface i.e. we will implement the two abstract
methods (Cube and Circle) of the Shape interface as shown in the below
code.

class Cube implements Shape


{
int x = 10;
public double Area ()
{
return (6 * x * x);
}
public double Volume ()
{
return (x * x * x);
}
}

class Circle implements Shape


{
int radious = 10;
public double Area ()
{
return (Math.PI * radious * radious);
}

public double Volume ()


{
return 0;
}
}

Now in the main method class, we will create an instance and consume
the two methods as shown in the below code.
public class Main
{
public static void main (String[]args)
{
Shape s1 = new Cube ();
System.out.println ("The area of Cube is : " + s1.Area ());
System.out.println ("The volume of Cube is : " + s1.Volume ());
Shape s2 = new Circle ();
System.out.println ("The area of Circle is : " + s2.Area ());
System.out.println ("The volume of Circle is : " + s2.Volume ());
}
}

Output:
Rules for implementing Java Interfaces

When implementation interfaces, there are several rules −

• A class can implement more than one interface at a time.


• A class can extend only one class, but implement many
interfaces.
• An interface can extend another interface, in a similar way as a
class can extend another class.

Points to Remember while working with Interfaces in Java:


• The interface doesn’t have any superclass/interface
• The default access specifier of the interface is the package
• Default access specifier of interface member is public
• By default, the interface members are public static final
variables and public abstract methods. If we don’t provide
these keywords compiler places these keywords automatically

How the interface is similar to a class in Java?


An interface is similar to a class in the following ways:
• An interface can contain any number of methods like class.
• An interface is written in a file with a .java extension, with the
name of the interface matching the name of the file.
• The byte code of an interface appears in a .class file.
• Interfaces appear in packages and their corresponding byte
code file must be in a directory structure that matches the
package name.

How the interface is different from a class in Java?


An interface is different from a class in the following ways:

• We cannot instantiate an interface.


• An interface does not contain any constructor.
• All of the methods of an interface are abstract.
• An interface cannot contain instance fields. The only fields that
can appear in an interface must be declared both static and
final.
• An interface is not extended by a class; it is implemented by a
class.
• An interface can extend multiple interfaces.

Rules to follow while working with Java Interface:


In developing, using, and deriving a subclass from an interface we must
follow the below rules.

• The interface cannot have concrete methods, violation leads to CE:


interface methods cannot have a body.
• In the interface we can have only public static final variables even if
we create variables as non-static, non-final variables compiler convert
it to the static final variable.
• We cannot declare interface members as private or protected
members violation leads to CE: “modifier is not allowed here”.
• Interface variables should be initialized at the time of creation
because they are final else it leads to compile-time error “=expected”.
• The interface cannot be instantiated but its reference variable can be
created for storing its subclass object reference.
• We cannot declare the interface as final it leads to CE: “illegal
combination of modifier interface and final”.
• The class derived from the interface should implement all abstract
methods of interface otherwise it should be declared as abstract else
it leads to a compile-time error.
• The subclass should implement the interface method with the public
keyword because the interface method’s default accessibility
modifier is public.

Example to Understand Interfaces in Java:


The following example is to implement multiple inheritances in Java.
class Student
{
int roll;
void getData (int p)
{
roll = p;
}
void Display ()
{
System.out.println ("Roll no is: " + roll);
}
}

class Test extends Student


{
double p1, p2;
void PutMarks (double x, double y)
{
p1 = x;
this.p2 = y;
}
void ShowMarks ()
{
System.out.println ("test1 = " + p1);
System.out.println ("test2 = " + p2);
}
}

interface Sports
{
double weight = 50.0;
void ShowWeight ();
}

class Results extends Test implements Sports


{
double total;
public void ShowWeight ()
{
System.out.println ("Weight = " + weight);
}
void DisplayAll()
{
total = p1 + p2 + weight;
Display ();
ShowMarks ();
ShowWeight ();
System.out.println ("The total is : " + total);
}
}

public class Main


{
public static void main (String[]args)
{
Results res = new Results();
res.getData(101);
res.PutMarks(55.5, 77.8);
res.DisplayAll();
}
}

Output:
Relationship Between Classes and Interfaces in Java:

Multiple inheritance in Java by interface

If a class implements multiple interfaces, or an interface extends multiple


interfaces, it is known as multiple inheritance.

What are the similarities between interface and abstract class in Java?
An interface is similar to an abstract class in the following ways
• Both interface and abstract class cannot be instantiated means we
cannot create an object.
• But we can create a reference variable for both interface and an
abstract class.
• The subclass should implement all abstract methods.
• Both cannot be declared final.
Difference Between Interface and Abstract Class in Java:
The main difference is to be answered in the interview is as follows

• The interface is a fully un-implemented class used for declaring a set of


operations of an object.
• An abstract class is a partially implemented class. It implements some
of the operations of the object that are declared in its interface. These
implemented operations are common for all next-level subclasses.
• The remaining operations are implemented by the next-level
subclasses according to their requirement.
• The interface allows us to develop multiple inheritances. So we must
start object design with an interface, whereas an abstract class does
not support multiple inheritances, so it always comes next to the
interface in the object creation process.

Except above, the following are some of the differences.


Interface in Java Abstract Class in java
The interface supports Abstract class does not support
Multiple Inheritance. Multiple Inheritance.
The interface doesn’t Abstract class contains Data
contain Data Members. Members.
The interface doesn’t Abstract Class contains
contain Constructors. Constructors.
An interface contains only An abstract class contains both
incomplete members. complete and incomplete
members.
An interface cannot have An abstract class can have access
access modifiers, by default, modifiers for the subs, functions,
everything is assumed as and properties.
public.
Members of the interface Only a complete member of the
cannot be Static. abstract class can be Static.
Should I use public access modifiers for interface methods in Java?
Java interface methods are implicitly public by default, even if they belong
to nested interfaces. Non-public modifiers are not valid or necessary for
interface methods. So, the compiler will fail and warn you in this case.
Nested interfaces may be declared protected or private, but not the
interface methods.

Can an interface extend an abstract class in Java?


No. In java, an interface cannot extend an abstract class. An interface may
only extend a super interface. However, an abstract class can implement
an interface because an abstract class can contain both abstract methods
and concrete methods.

Can an interface be declared as final in Java?


No, it is not permitted to declare an interface as final; it will cause a
compilation error. This is a java language design decision. Interface types
are intended to be implemented and can be extended without restriction.

Is more than one interface are allowed to implement a class in Java?


Yes, a class can implement multiple interfaces, this is an effective way to
achieve multiple inheritances in java. But a class can extend only one
superclass.

Is it necessary to implement all interface methods in Java?


It is not necessary for a class that implements an interface to implement
all its methods, but in this case, the class must be declared as abstract.

Can an interface variable be overridden in Java?


No, interface variables are constants that cannot be overridden. They are
inherited by any class that implements an interface

You might also like