Another way to achieve abstarction in Java, is with interfaces.
What is interface?
Interfaces form a contract(Set of rules) between the class and the outside world, and this contract is enforced at build time by the compiler.
An interface(completely “abstract class“) is a group of related methods with empty bodies.
To implements this interface, the name of your class would change , and you’d use the implements keyword in the class declaration.
Notes on interface:
- Like abstract classes, interfaces cannot be used to create objects.So, it cannot contain a constructor .
- Interface methods do not have a body – the body is provided by the “implement” class.
- On implementation of an interface, you must override all of its methods.
- Interface methods are by default abstract and public.
- Interface attributes are by default public, static and final.
- Why And When To Use Interfaces?
- 1) To achieve security – hide certain details and only show the important details of an object (interface).
- 2) Java does not support “multiple inheritance” (a class can only inherit from one superclass). However, it can be achieved with interfaces, because the class can implement multiple interfaces.
Java Interface Example
In this example, the Printable interface has only one method, and its implementation is provided in the A6 class.
- interface printable{
- void print();
- }
- class A6 implements printable{
- void print()
- {
- System.out.println(“Hello”);
- }
- public static void main(String args[]){
- A6 obj = new A6();
- obj.print();
- }
- }
Reference,
https://www.w3schools.com/java/tryjava.asp