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 }
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(); }
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."); } }
Now, you can use the Shape interface as follows:
Shape shape = new Circle(); shape.draw(); // Prints: I'm a circle.
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!