Java interface
Created By: chatGPT
In Java, an interface is a reference type that is similar to a class. It is a collection of abstract methods (methods that do not have a body) that classes can implement. In other words, an interface defines a contract that other classes can choose to follow. Implementing an interface allows a class to inherit the abstract methods of the interface and provide their own implementation for them.
public interface Animal {
void eat();
void sleep();
}
A class that implements an interface must provide implementations for all of its methods. If a class does not implement all methods, it must be declared as an abstract class itself. Here's an example of a class implementing the Animal interface defined above:
public class Dog implements Animal {
@Override
public void eat() {
System.out.println("Dog is eating");
}
@Override
public void sleep() {
System.out.println("Dog is sleeping");
}
}
In Java, a class can implement multiple interfaces, which allows for a greater degree of flexibility and reusability. However, interfaces can only extend other interfaces. Here’s how to implement multiple interfaces:
public interface Vehicle {
void drive();
}
public interface Machine {
void start();
}
public class Car implements Vehicle, Machine {
@Override
public void drive() {
System.out.println("Car is driving");
}
@Override
public void start() {
System.out.println("Car has started");
}
}
Java interfaces can also contain default methods and static methods. Default methods allow the interface to have a method implementation, which means that classes implementing the interface do not necessarily have to implement this method. Static methods can be called on the interface itself without needing an instance of a class.
In summary, interfaces in Java are a powerful way to achieve abstraction and multiple inheritance by allowing classes to implement multiple interfaces. They enable polymorphism, where different classes can be treated as instances of the same interface type, making your code more flexible and extensible.public interface Device {
default void turnOn() {
System.out.println("Device is now ON");
}
static void reset() {
System.out.println("Device has been reset");
}
}
public class Smartphone implements Device { }
// Usage
Device smartphone = new Smartphone();
smartphone.turnOn();
Device.reset();