Java Interface example

  1. /*

  2. Java Interface example.

  3. This Java Interface example describes how interface is defined and

  4. being used in Java language.

  5.  

  6. Syntax of defining java interface is,

  7. <modifier> interface <interface-name>{

  8.   //members and methods()

  9. }

  10. */

  11.  

  12. //declare an interface

  13. interface IntExample{

  14.  

  15. /*

  16.   Syntax to declare method in java interface is,

  17.   <modifier> <return-type> methodName(<optional-parameters>);

  18.   IMPORTANT : Methods declared in the interface are implicitly public and abstract.

  19.   */

  20.  

  21. public void sayHello();

  22. }

  23. }

  24. /*

  25. Classes are extended while interfaces are implemented.

  26. To implement an interface use implements keyword.

  27. IMPORTANT : A class can extend only one other class, while it

  28. can implement n number of interfaces.

  29. */

  30.  

  31. public class JavaInterfaceExample implements IntExample{

  32. /*

  33.   We have to define the method declared in implemented interface,

  34.   or else we have to declare the implementing class as abstract class.

  35.   */

  36.  

  37. public void sayHello(){

  38. System.out.println("Hello Visitor !");

  39. }

  40.  

  41. public static void main(String args[]){

  42. //create object of the class

  43. JavaInterfaceExample javaInterfaceExample = new JavaInterfaceExample();

  44. //invoke sayHello(), declared in IntExample interface.

  45. javaInterfaceExample.sayHello();

  46. }

  47. }

  48.  

  49. /*

  50. OUTPUT of the above given Java Interface example would be :

  51. Hello Visitor !

  52. */

0 comments: