Java Interface Example /* Java Interface example. This Java Interface example describes how interface ...

Java Interface Example

02:31 PASSOVE INCOME 0 Comments

                  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. Syntax of defining java interface is,
  6. <modifier> interface <interface-name>{
  7.   //members and methods()
  8. }
  9. */
  10. //declare an interface
  11. interface IntExample{
  12.   /*
  13.   Syntax to declare method in java interface is,
  14.   <modifier> <return-type> methodName(<optional-parameters>);
  15.   IMPORTANT : Methods declared in the interface are implicitly public and abstract.
  16.   */
  17.   public void sayHello();
  18.   }
  19. }
  20. /*
  21. Classes are extended while interfaces are implemented.
  22. To implement an interface use implements keyword.
  23. IMPORTANT : A class can extend only one other class, while it
  24. can implement n number of interfaces.
  25. */
  26. public class JavaInterfaceExample implements IntExample{
  27.   /*
  28.   We have to define the method declared in implemented interface,
  29.   or else we have to declare the implementing class as abstract class.
  30.   */
  31.   public void sayHello(){
  32.     System.out.println("Hello Visitor !");
  33.   }
  34.   public static void main(String args[]){
  35.     //create object of the class
  36.     JavaInterfaceExample javaInterfaceExample = new JavaInterfaceExample();
  37.     //invoke sayHello(), declared in IntExample interface.
  38.     javaInterfaceExample.sayHello();
  39.   }
  40. }
  41. /*
  42. OUTPUT of the above given Java Interface example would be :
  43. Hello Visitor !
  44. */

0 comments: