Join
Blogs
Questions
Videos
Tags
Members
Search
 
 
Create your own blog, earn points and get popular!

Java Interface Example

  1. /*
  2. Java Interface example.
  3. This Java Interface example describes how interface is defined and being
  4. used in Java language.
  5. */
  6.  
  7. /*
  8. Syntax of defining java interface is,
  9.  
  10.     <modifier> interface <interface-name>{
  11.         //members and methods()
  12.     }
  13. */
  14.  
  15. //declare an interface
  16. interface IntExample{
  17.    
  18.     /*
  19.     Syntax to declare method in java interface is,
  20.    
  21.         <modifier> <return-type> methodName(<optional-parameters>);
  22.    
  23.     IMPORTANT : Methods declared in the interface are implicitly public
  24.     and abstract.
  25.     */
  26.    
  27.     public void sayHello();
  28.  
  29. }
  30.  
  31. /*
  32.  
  33. Classes are extended while interfaces are implemented.
  34. To implement an interface use implements keyword.
  35. IMPORTANT : A class can extend only one other class, while it can
  36. implement n number of interfaces.
  37.  
  38. */
  39.  
  40. public class JavaInterfaceExample implements IntExample{
  41.  
  42.     /*
  43.     We have to define the method declared in implemented interface,    
  44.     or else we have to declare the implementing class as abstract class.
  45.     */
  46.    
  47.     public void sayHello(){
  48.         System.out.println("Hello Visitor !");
  49.     }
  50.    
  51.     public static void main(String args[]){
  52.    
  53.         //create object of the class
  54.         JavaInterfaceExample javaInterfaceExample = new JavaInterfaceExample();
  55.        
  56.         //invoke sayHello(), declared in IntExample interface.
  57.         javaInterfaceExample.sayHello();
  58.    
  59.     }
  60.  
  61. }
  62.  
  63. /*
  64. OUTPUT of the above given Java Interface example would be:
  65. Hello Visitor !
  66. */
Your rating: None Average: 1.9 (13 votes)
Share this