Monday, 28 November 2016

Program to create a interface 'Mango' and implement it in classes 'Winter' and 'Summer'

This program demonstrate you the hierarchical inheritance in Java which contains one interface Mango and the other two subclasses Summer and Winter implement this interface using implements keyword. The syntax for declaring interface is given below:
interface <interface-name> {
    // variable declarations
 // Method declarations (no implementation)
}

The implements keyword is used to for implementing interface and extends keyword is used to extend the class. The syntax for extending class and implementing interface is:
class <subclass-name> extends <superclass-name> implements <interface-name> {

 // Body of subclass
}

You cannot create an object of interface but you can create a reference of it. Like,
Mango  m;

PROGRAM
//Creating interface 'Mango' having display( ) method.
interface Mango {
 
 void display();
}

//Implementing interface 'Mango'.
class Summer implements Mango {
 
 // Overriding 'display( )' method.
 public void display() {
  
  System.out.println("Display method in Summer ... ");
 }
}

//Implementing interface 'Mango'.
class Winter implements Mango {
 
 //Overriding 'display( )' method.
 public void display() {
  
  System.out.println("Display method in Winter ...");
 }
}

class MyInterface {
 
 public static void main(String args[]) {
  
  Mango m = new Summer(); //statement1
  Winter n = new Winter();
  m.display();
  m = n; //assigning the reference
  m.display();
 }
}
OUTPUT
C:\>javac MyInterface.java
C:\>java MyInterface
Display method in Summer ... 
Display method in Winter ...

No comments:

Post a Comment