In Java, an interface is a reference type, similar to a class, that can contain only constants, method signatures, default methods, static methods, and nested types. Interfaces cannot contain instance fields or constructors. Interfaces are a way to achieve abstraction and multiple inheritance in Java.
Once an interface is defined, a class can implement it by providing the body for the methods defined in the interface. A class that implements an interface must implement all the methods declared in the interface unless the class is abstract.
Interfaces are widely used in Java for various purposes such as polymorphism, achieving loose coupling, and enforcing a contract for the classes that implement them.
// Example of an interface in Java
interface Animal {
void sound(); // interface method (does not have a body)
}
class Dog implements Animal {
public void sound() {
System.out.println("Woof");
}
}
public class Main {
public static void main(String[] args) {
Dog dog = new Dog();
dog.sound(); // Outputs: Woof
}
}
How do I avoid rehashing overhead with std::set in multithreaded code?
How do I find elements with custom comparators with std::set for embedded targets?
How do I erase elements while iterating with std::set for embedded targets?
How do I provide stable iteration order with std::unordered_map for large datasets?
How do I reserve capacity ahead of time with std::unordered_map for large datasets?
How do I erase elements while iterating with std::unordered_map in multithreaded code?
How do I provide stable iteration order with std::map for embedded targets?
How do I provide stable iteration order with std::map in multithreaded code?
How do I avoid rehashing overhead with std::map in performance-sensitive code?
How do I merge two containers efficiently with std::map for embedded targets?