Search This Blog

Tuesday, 30 December 2014

Defining and Implementing Multiple Interfaces in Java

0 comments
IMPLEMENTING MULTIPLE INHERITANCE IN A CLASS

AIM: To write a program in Java to implement two interfaces in a single class.


PROCEDURE:
  1. Define two Interfaces named Square and Rectangle with method a single method computeArea(), which is overloaded with their various parameters.
  2. Implement both interfaces in a class named Area by providing code for computeArea() of both interfaces.
  3. Implement the method main() in another java file named MulInterface.java for creating the objects of Area and to compute the area for both square and rectangle.
  4. In method main(), declare the variables s, l and w of type float. Also create input object - din of type DataInputStream
  5. Declare a variable (objA) of type Area and create an object for it.
  6. Get the value of s from the user and call the method computeArea() of objA with s as the parameter to compute the area of square.
  7. Get the value of l and w from the user and call the method computeArea() of objA with l and w as parameters to compute the area of rectangle.
  8. Display the result – area of square and area of rectangle


PROGRAM:
Area.java
interface Square
{
int sides = 3;
float computeArea(float side);
}


interface Rectangle
{
int sides = 4;
float computeArea(float length, float width);
}




public class Area implements Square, Rectangle
{
public float computeArea(float s)
{
return (s * s);
}
public float computeArea(float l, float w)
{
return (l * w);
}
}


MulInterface.java
import java.io.*;
public class MulInterface {


/**
* @param args the command line arguments
*/
public static void main(String[] args) throws IOException
{
float s, l, w;
DataInputStream din = new DataInputStream(System.in);
Area objA = new Area();
System.out.println("Enter the value of s (Side of a Square) : ");
s = Float.parseFloat(din.readLine());
System.out.println("The Area of the Square is : " + objA.computeArea(s));
System.out.println("Enter the value of l (Length of a Rectangle) : ");
l = Float.parseFloat(din.readLine());
System.out.println("Enter the value of w (Width of a Rectangle) : ");
w = Float.parseFloat(din.readLine());
System.out.println("The Area of the Rectangle is : " + objA.computeArea(l,w));
}
}


Sample Run:

Leave a Reply