Search code examples
javaclassinterfaceimplements

Interface Method Usage(Java)?


Can Someone Explain how the methods of interface used in classes?

Note: My Doubt is "Methods are already defined in Class then why we should implement it ? "

For Example :

interface printable{
void print();
}

class A implements printable{
public void print(){System.out.println("Hello");}

public static void main(String args[]){
A obj = new A();
obj.print();
 }
}

why print() is declared in interface??


Solution

  • You define a method by giving its implementation. They are the same thing, so you are right that once you define a method, you don't also need to implement it.

    An interface declares that anything implementing this interface will defined those methods. This is part of the contract for interfaces. This allows you to call any method of an interface knowing than any concrete implementation will have such a method.

    BTW In Java 8, it will support virtual extensions which means an interface can give a default implementation. This has to be defined in terms of other methods provided by the interface.