#
Interfaces in Java
#
Interfaces in Java - explanation
Abstraction in general hide the implementation details from the user. We can see WHAT an object can do, but not HOW. Abstraction in Java is realized by using abstract classes and interfaces.
An interface
class in Java is a class which:
- define a collection of
public
andabstract
methods (which will be implemented later) - could define a collection of
public
,static
&final
variables - (starting from Java 8) could define a
default
method and somestatic
methods
Info
A class can implement more than one interfaces, however it cannot extend more than one class.
Info
As we can see starting from Java 8, the interfaces could contain implementation for some methods (static
or default
).
#
Interfaces in Java - example
Here is an interface definition:
Shape.java
public interface Shape {
void drawShape();
void eraseShape();
}
Here is the class which implements the interface class:
Triangle.java
public class Triangle implements Shape {
public void drawShape() {
System.out.println("Draw shape from Triangle Class.");
}
public void eraseShape() {
System.out.println("Erase shape from Triangle Class.");
}
}
Here is the code of the main class:
MyApp.java
public class MyApp {
public static void main(String [] args) {
Triangle triangle = new Triangle();
triangle.drawShape();
triangle.eraseShape();
}
}
Note:
- a class could extend a class
- a class could implement an interface