Vous êtes sur la page 1sur 2

y * y Java Interface example.

y This Java Interface example describes how interface is defined and y being used in Java language. y y Syntax of defining java interface is, y <modifier> interface <interface-name>{ y //members and methods() y } y */ y y //declare an interface y interface IntExample{ y y /* y Syntax to declare method in java interface is, y <modifier> <return-type> methodName(<optional-parameters>); y IMPORTANT : Methods declared in the interface are implicitly public and abstract. y */ y y public void sayHello(); y } y } y /* y Classes are extended while interfaces are implemented. y To implement an interface use implements keyword. y IMPORTANT : A class can extend only one other class, while it y can implement n number of interfaces. y */ y y public class JavaInterfaceExample implements IntExample{ y /* y We have to define the method declared in implemented interface, y or else we have to declare the implementing class as abstract class. y */ y y public void sayHello(){ y System.out.println("Hello Visitor !"); y } y y public static void main(String args[]){ y //create object of the class y JavaInterfaceExample javaInterfaceExample = new JavaInterfaceExample(); y //invoke sayHello(), declared in IntExample interface. y javaInterfaceExample.sayHello(); y } y } y

y y y y

/* OUTPUT of the above given Java Interface example would be : Hello Visitor ! */