Interfaces
This lesson discusses interfaces in Java.
We'll cover the following...
Question # 1
What is an interface in Java
An interface can be thought of as a contract an implementing object has with its consumers. An interface will define the methods or API exposed by the implementing object. The consumers will rely on the method defined by the interface to interact with the implementing object. An interface allows us to hide the implementation details from the consumer. The object implementing the interface can change the functionality or be switched out for a completely different object that also implements the same interface. The consumer is only knowledgeable about the interface and not the concrete classes that implement it. This makes the code more flexible and maintainable.
Interface Example
public interface PersonActions {
void sayHello();
}
Methods in an interface that are not declared as default or static are implicitly abstract.
Question # 2
What is the difference between an interface and an abstract class in Java?
Following are the main differences between an abstract class and an interface
An abstract class can have final, static, or class member variables whereas an interface can only have variables that are final and static by default.
An abstract class can have static, abstract, or non-abstract methods. An interface can have static, abstract, or default methods. ...