[Go to site: main page, start]

0% found this document useful (0 votes)
14 views12 pages

Understanding Java Interfaces Tutorial

The document discusses Java interfaces, including how to define an interface, implement an interface, extend interfaces, use default and static methods in interfaces, and provides examples of interfaces.

Uploaded by

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

Understanding Java Interfaces Tutorial

The document discusses Java interfaces, including how to define an interface, implement an interface, extend interfaces, use default and static methods in interfaces, and provides examples of interfaces.

Uploaded by

Ven Dicator
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd

Java Interface

In this tutorial, we will learn about Java interfaces. We will learn how to
implement interfaces and when to use them in detail with the help of
examples.

An interface is a fully abstract class. It includes a group of abstract methods


(methods without a body).

We use the interface keyword to create an interface in Java. For example,

interface Language {
public void getType();

public void getVersion();


}

Here,

 Language is an interface.
 It includes abstract methods: getType() and getVersion() .

Implementing an Interface
Like abstract classes, we cannot create objects of interfaces.

To use an interface, other classes must implement it. We use


the implements keyword to implement an interface.
Example 1: Java Interface
interface Polygon {
void getArea(int length, int breadth);
}

// implement the Polygon interface


class Rectangle implements Polygon {

// implementation of abstract method


public void getArea(int length, int breadth) {
[Link]("The area of the rectangle is " + (length * breadth));
}
}

class Main {
public static void main(String[] args) {
Rectangle r1 = new Rectangle();
[Link](5, 6);
}
}
Run Code

Output

The area of the rectangle is 30

In the above example, we have created an interface named Polygon . The


interface contains an abstract method getArea() .

Here, the Rectangle class implements Polygon . And, provides the implementation
of the getArea() method.

Example 2: Java Interface


// create an interface
interface Language {
void getName(String name);
}
// class implements interface
class ProgrammingLanguage implements Language {

// implementation of abstract method


public void getName(String name) {
[Link]("Programming Language: " + name);
}
}

class Main {
public static void main(String[] args) {
ProgrammingLanguage language = new ProgrammingLanguage();
[Link]("Java");
}
}
Run Code

Output

Programming Language: Java

In the above example, we have created an interface named Language . The


interface includes an abstract method getName() .

Here, the ProgrammingLanguage class implements the interface and provides the
implementation for the method.

Implementing Multiple Interfaces

In Java, a class can also implement multiple interfaces. For example,

interface A {
// members of A
}
interface B {
// members of B
}

class C implements A, B {
// abstract members of A
// abstract members of B
}

Extending an Interface
Similar to classes, interfaces can extend other interfaces. The extends keyword
is used for extending interfaces. For example,

interface Line {
// members of Line interface
}

// extending interface
interface Polygon extends Line {
// members of Polygon interface
// members of Line interface
}

Here, the Polygon interface extends the Line interface. Now, if any class
implements Polygon , it should provide implementations for all the abstract
methods of both Line and Polygon .
Extending Multiple Interfaces

An interface can extend multiple interfaces. For example,

interface A {
...
}
interface B {
...
}

interface C extends A, B {
...
}

Advantages of Interface in Java


Now that we know what interfaces are, let's learn about why interfaces are
used in Java.

 Similar to abstract classes, interfaces help us to achieve abstraction in


Java.

Here, we know getArea() calculates the area of polygons but the way
area is calculated is different for different polygons. Hence, the
implementation of getArea() is independent of one another.
 Interfaces provide specifications that a class (which implements it)
must follow.
In our previous example, we have used getArea() as a specification
inside the interface Polygon . This is like setting a rule that we should be
able to get the area of every polygon.

Now any class that implements the Polygon interface must provide an
implementation for the getArea() method.
 Interfaces are also used to achieve multiple inheritance in Java. For
example,

 interface Line {
 …
 }

 interface Polygon {
 …
 }

 class Rectangle implements Line, Polygon {
 …

Here, the class Rectangle is implementing two different interfaces. This is


how we achieve multiple inheritance in Java.
Note: All the methods inside an interface are implicitly public and all fields are
implicitly public static final . For example,

interface Language {

// by default public static final


String type = "programming language";
// by default public
void getName();
}

default methods in Java Interfaces


With the release of Java 8, we can now add methods with implementation
inside an interface. These methods are called default methods.

To declare default methods inside interfaces, we use the default keyword. For
example,

public default void getSides() {


// body of getSides()
}

Why default methods?

Let's take a scenario to understand why default methods are introduced in


Java.

Suppose, we need to add a new method in an interface.

We can add the method in our interface easily without implementation.


However, that's not the end of the story. All our classes that implement that
interface must provide an implementation for the method.
If a large number of classes were implementing this interface, we need to
track all these classes and make changes to them. This is not only tedious but
error-prone as well.

To resolve this, Java introduced default methods. Default methods are


inherited like ordinary methods.

Let's take an example to have a better understanding of default methods.

Example: Default Method in Java Interface


interface Polygon {
void getArea();

// default method
default void getSides() {
[Link]("I can get sides of a polygon.");
}
}

// implements the interface


class Rectangle implements Polygon {
public void getArea() {
int length = 6;
int breadth = 5;
int area = length * breadth;
[Link]("The area of the rectangle is " + area);
}

// overrides the getSides()


public void getSides() {
[Link]("I have 4 sides.");
}
}
// implements the interface
class Square implements Polygon {
public void getArea() {
int length = 5;
int area = length * length;
[Link]("The area of the square is " + area);
}
}

class Main {
public static void main(String[] args) {

// create an object of Rectangle


Rectangle r1 = new Rectangle();
[Link]();
[Link]();

// create an object of Square


Square s1 = new Square();
[Link]();
[Link]();
}
}
Run Code

Output

The area of the rectangle is 30


I have 4 sides.
The area of the square is 25
I can get sides of a polygon.

In the above example, we have created an interface named Polygon . It has a


default method getSides() and an abstract method getArea() .

Here, we have created two classes Rectangle and Square that implement Polygon .

The Rectangle class provides the implementation of the getArea() method and
overrides the getSides() method. However, the Square class only provides the
implementation of the getArea() method.
Now, while calling the getSides() method using the Rectangle object, the
overridden method is called. However, in the case of the Square object, the
default method is called.

private and static Methods in Interface


The Java 8 also added another feature to include static methods inside an
interface.

Similar to a class, we can access static methods of an interface using its


references. For example,

// create an interface
interface Polygon {
staticMethod(){..}
}

// access static method


[Link]();

Note: With the release of Java 9, private methods are also supported in
interfaces.
We cannot create objects of an interface. Hence, private methods are used as
helper methods that provide support to other methods in interfaces.

Practical Example of Interface


Let's see a more practical example of Java Interface.

// To use the sqrt function


import [Link];

interface Polygon {
void getArea();

// calculate the perimeter of a Polygon


default void getPerimeter(int... sides) {
int perimeter = 0;
for (int side: sides) {
perimeter += side;
}

[Link]("Perimeter: " + perimeter);


}
}

class Triangle implements Polygon {


private int a, b, c;
private double s, area;

// initializing sides of a triangle


Triangle(int a, int b, int c) {
this.a = a;
this.b = b;
this.c = c;
s = 0;
}

// calculate the area of a triangle


public void getArea() {
s = (double) (a + b + c)/2;
area = [Link](s*(s-a)*(s-b)*(s-c));
[Link]("Area: " + area);
}
}

class Main {
public static void main(String[] args) {
Triangle t1 = new Triangle(2, 3, 4);
// calls the method of the Triangle class
[Link]();

// calls the method of Polygon


[Link](2, 3, 4);
}
}
Run Code

Output

Area: 2.9047375096555625
Perimeter: 9

In the above program, we have created an interface named Polygon . It includes


a default method getPerimeter() and an abstract method getArea() .

We can calculate the perimeter of all polygons in the same manner so we


implemented the body of getPerimeter() in Polygon .

Now, all polygons that implement Polygon can use getPerimeter() to calculate
perimeter.
However, the rule for calculating the area is different for different polygons.
Hence, getArea() is included without implementation.
Any class that implements Polygon must provide an implementation of getArea() .

REFERENCES: [Link]

Common questions

Powered by AI

Interfaces in Java support polymorphism by allowing objects to be referenced by their interface types rather than their actual class type. This means that an object of any class implementing an interface can be accessed through a reference of that interface type, enabling method calls on the interface's methods. This abstraction allows code to interact with objects through a common interface without knowing the object's specific class, facilitating flexibility and interchangeability of objects at runtime . For example, both Rectangle and Triangle classes implementing the Polygon interface can be used interchangeably through a Polygon reference .

When using interfaces, developers may face several challenges. Firstly, designing the interface itself requires foresight to ensure it captures all possible use cases while maintaining simplicity and clarity. Second, excessive reliance on interfaces can lead to a proliferation of interfaces that overcomplicate the codebase, making it hard to maintain. Additionally, implementing multiple interfaces may require a class to offer a multitude of potentially conflicting implementations, which may cause subtle bugs and increase complexity . Interfaces also offer no support for constructors or instance variable states, which can limit their capacity to offer complete template solutions without additional design structures such as abstract classes .

An interface in Java can extend multiple interfaces, allowing it to inherit the abstract methods of multiple parents. For example, interface C extends interfaces A and B: `interface A { void methodA(); } interface B { void methodB(); } interface C extends A, B { }`. Here, any class implementing interface C would need to provide implementations for methodA() and methodB(). This feature is advantageous because it allows Java to avoid multiple inheritance from classes while still benefiting from it through interfaces, leading to a more flexible and decoupled design. It helps developers create versatile interfaces that can be built upon to achieve more complex interactions without the complications of class-based multiple inheritance .

Abstract classes in Java can have both abstract and non-abstract methods, whereas interfaces are fully abstract and only contain abstract methods (prior to Java 8). Interfaces allow a class to implement multiple types, as Java supports multiple interface inheritance but not multiple class inheritance . A class should implement an interface when it needs to assure it follows a specific set of methods (functions). In contrast, abstract classes are used when there is a common base with shared code and state that should not be obligatory in all derived classes. An interface provides a form of contract or specification that a class must adhere to, while an abstract class provides partial implementation for derived classes .

Polymorphic behavior through interface references in Java allows a single interface reference to point to objects of different implementing classes. This is significant because it provides the flexibility to change the concrete class implementation without altering the code that uses the interface. Consequently, it facilitates the creation of more adaptable, modular applications since the implementation details can vary independently of the composite system structure. The approach enhances the capability to extend or modify an application solely by introducing new classes that implement the same interface, boosting maintainability and scalability .

Java handles multiple inheritance through interfaces, which allows a class to implement multiple interfaces, each acting as a type that the class must adhere to. This differs from languages like C++, which allow multiple inheritance directly through classes. Java avoids the complexity and potential ambiguity, such as the "diamond problem," by providing multiple inheritance of type via interfaces without inheriting implementation, while C++ allows classes to inherit both the implementation and interface from multiple base classes . Thus, Java's approach is safer and more structured, sticking strictly to the contract-based programming model of interfaces .

The introduction of default and static methods in Java interfaces has blurred the traditional boundaries between interfaces and abstract classes. Originally, interfaces were seen strictly as contracts without any implementation, while abstract classes provided partial implementation. The ability to include default methods gives interfaces some implementation power, traditionally the domain of abstract classes, thereby enriching them with behaviors that previous implementations of all interface-adhering classes could inherit. Static methods in interfaces likewise extend their utility without requiring inheritance . This shift allows for greater flexibility in designing APIs and systems, as developers can decide more freely on using interfaces as foundational architectures that house common utilities and default behaviors traditionally creased in an abstract class .

A developer might declare a method static within an interface to provide utility methods that don't require an instance of the interface to be used. Static methods in interfaces can be accessed using the interface name, similar to static methods in classes. This means they act much like class utility methods, but are associated with the concept represented by the interface rather than a specific implementation. For instance, if a Polygon interface had a static method, it could be accessed via Polygon.someStaticMethod(). These methods can be used to perform operations applicable to all implementing classes or provide common functionalities .

Default methods in Java interfaces, introduced in Java 8, allow developers to add new methods to interfaces without breaking the existing implementations of those interfaces. By providing a default implementation, any class implementing the interface won't be forced to implement the new method unless it needs specific behavior, thus maintaining backward compatibility . This is particularly useful when a new method needs to be added to an already widely implemented interface without requiring all implementing classes to define the new method, reducing errors and easing code maintenance .

Private methods in Java interfaces, introduced in Java 9, serve as helper methods that can encapsulate code common to multiple default methods in an interface. They enable code reuse within the interface itself without exposing these methods to the implementing classes, thus keeping the interface streamlined and focused on its role as an API specification. This encapsulation also reduces code duplication and enhances maintainability by localizing changes to these utilities within the interface . Private methods are significant for their ability to de-clutter interfaces and ensure internal logic can be managed privately—closely aligning interface design with class design principles while keeping implementation hidden .

You might also like