Home > Java > javaTutorial > What is an Interface in Java and How Does it Work?

What is an Interface in Java and How Does it Work?

Patricia Arquette
Release: 2024-11-06 17:02:02
Original
557 people have browsed it

What is an Interface in Java and How Does it Work?

What is an Interface in Java?

An interface is a special type of abstract class used in object-oriented programming languages like Java.

In Java, an interface is defined as follows:

interface Interface {
    // Declare abstract methods
}
Copy after login

Unlike abstract classes, interfaces cannot implement methods. Instead, they define abstract methods that must be implemented in the classes that implement the interface. Here's an example of an interface:

interface Shape {
    void draw();
}
Copy after login

To use an interface, a class must implement it, which means it must provide implementations for all the abstract methods in the interface. Multiple classes can implement the same interface, and a class can implement multiple interfaces.

For example:

class Circle implements Shape {
    public void draw() { System.out.println("I'm a circle."); }
}

class Square implements Shape {
    public void draw() { System.out.println("I'm a square."); }
}
Copy after login

Now, you can use the Shape interface as follows:

Shape shape = new Circle();
shape.draw(); // Prints: I'm a circle.
Copy after login

Interfaces are used widely in Java for loose coupling and polymorphism. They allow classes to define common behaviors without explicitly specifying a concrete implementation. This promotes code reusability, flexibility, and extensibility.

The above is the detailed content of What is an Interface in Java and How Does it Work?. For more information, please follow other related articles on the PHP Chinese website!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template