// interfaceinterfaceAnimal{publicvoidanimalSound();// interface method (does not have a body)publicvoidrun();// interface method (does not have a body)}
Aninterface can contain:public constants;abstract methods without an implementation (the keyword abstract is not required here);default methods withimplementation(the keyword default is required);static methods withimplementation(the keyword static is required);private methods withimplementation.Java9 onwards, you can include private methods in interfaces. BeforeJava9
it was not possible.
Aninterface can't contain fields (only constants), constructors,
or non-publicabstractmethods.
The keyword abstract before a method means that the method does not have a
body, it just declares a signature.
// Assume we have the simple interface:interfaceAppendable{voidappend(string content);}// We can implement it like that:classSimplePrinterimplementsAppendable{publicvoidappend(string content){System.out.println(content);}}// ... and maybe like that:classFileWriterimplementsAppendable{publicvoidappend(string content){// Appends content into a file }}// Both classes are Appendable.0
how toimplement a interface in java
the main idea of an interface is declaring functionality.
Suppose you program a game that has several types of characters.
These characters are able tomove within a map. That is represented by Movableinterface
interfaceInterface{intINT_CONSTANT=0;// it's a constant, the same as public static final int INT_FIELD = 0voidinstanceMethod1();voidinstanceMethod2();staticvoidstaticMethod(){System.out.println("Interface: static method");}defaultvoiddefaultMethod(){System.out.println("Interface: default method. It can be overridden");}privatevoidprivateMethod(){System.out.println("Interface: private methods in interfaces are acceptable but should have a body");}}Static,default, and private methods should have an implementation in the interface!
In many cases, it is more important toknow what an object can do,instead of
how it does what it does. This is a reason why interfaces are commonly used for
declaring a type of variable.interface:DrawingTool: a tool can draw
interfaceDrawingTool{voiddraw(Curve curve);}DrawingTool pencil =newPencil();DrawingTool brush =newBrush();BothPencil and brush class should implement draw method
// Java program to demonstrate working of// interfaceimportjava.io.*;// A simple interfaceinterfaceIn1{// public, static and finalfinalint a =10;// public and abstractvoiddisplay();}// A class that implements the interface.classTestClassimplementsIn1{// Implementing the capabilities of// interface.publicvoiddisplay(){System.out.println("Geek");}// Driver Codepublicstaticvoidmain(String[] args){TestClass t =newTestClass();
t.display();System.out.println(a);}}