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 ...

Popular posts from this blog

Program to define a class 'employee' with data members as empid, name and salary. Accept data for 5 objects using Array of objects and print it.

Define a class Student with four data members such as name, roll no.,sub1, and sub2. Define appropriate methods to initialize and display the values of data members. Also calculate total marks and percentage scored by student.

Program to input age from user and throw user-defined exception if entered age is negative