An interface is declared with the keyword interface.
An interface has no constructors or instance variables. Interfaces cannot be instantiated.
All methods of an interface are public and abstract, there is no need to put "public abstract" in front of each method.
Interfaces are implemented using the keyword implements.
A class can implement any number of interfaces.
If a class implements an interface, that it must supply all the methods listed in the interface unless the class is declared as abstract.
When supplying a method to implement an interface, the method must have the exact same signature (name + parameter(s)) and return type as declared in the interface.
public interface testInterface {
String testMethod(String s);
}
//The example below is correct
public class testClass implements testInterface
{
public String testMethod(String s)
{
return "test";
}
}
//The example below causes compile-time error: The return type is incompatible. Not all the Object is a String.
public class testClass implements testInterface
{
public Object testMethod(String s)
{
return "test";
}
}
//The example below causes compile-time error: The type testClass must implement the inherited abstract method
public class testClass implements testInterface
{
public String testMethod(Object s)
{
return "test";
}
}
public interface testInterface
{
Object testMethod(Object s);
}
//The example below is correct
public class testClass implements testInterface
{
public Object testMethod(Object s)
{
return "test";
}
}
//The example below is correct. String is a Object.
public class testClass implements testInterface
{
public String testMethod(Object s)
{
return "test";
}
}
//The example below causes compile-time error: The type testClass must implement the inherited abstract method.
public class testClass implements testInterface
{
public Object testMethod(String s)
{
return "test";
}
}
if extends an implements are used together, the extends clause must precede the implements clause.
Example: public class SubClass extends SuperClass implements Interface1, Interface2, …
Like a superclass, an interface provides a secondary data type to the objects of classes that implement that interface, and polymorphism works for interface types.
If a class implements an interface, then all subclasses also implement that interface. It is not necessary to implements again.
Java 101: Interfaces in Java - http://www.javaworld.com/article/3171300/java-language/java-101-interfaces-in-java.html
Interface in Java - https://www.javatpoint.com/interface-in-java