Java program to find the area of rectangle and triangle using Interface
Write a Java program to define an interface called Area which contains a method called Compute() and calculate areas of the rectangle(I*b) and triangle(1/2*b*h) using classes Rectangle and Triangle.
Video Tutorial:
Step1: Create an interface in Java as shown below:
public interface Area { double Compute(double a, double b); }
In the above code snippet, we have created an interface Area. This interface contains one method called Compute, which returns double and accepts two double-type arguments.
Step 2: Create a Java program to implement the above interface as shown below.
class Rectangle implements Area { public double Compute(double l, double b) { return (l*b); } } class Triangle implements Area { public double Compute(double b, double h) { return (b*h/2); } } public class MainArea { public static void main(String args[]) { Rectangle rect = new Rectangle(); double RArea = rect.Compute(10, 20); System.out.println("The area of the Rectangle is "+RArea); Triangle tri = new Triangle(); double TArea = tri.Compute(10, 20); System.out.println("The area of the triangle is "+TArea); } }
In the above code snippet, we have created three classes, Rectangle, Triangle, and MainArea. The classes Rectangle and Triangle implements the interface Area. Hence these two classes define the method Compute.
The MainArea class creates an object of Rectangle and Triangle. Using these objects the Compute method is called. Finally, the result is displayed.
Output:
The area of the Rectangle is 200.0
The area of the triangle is 100.0
Summary:
This tutorial discusses, how to write a Java program to find the area of rectangle and triangle using Interface. If you like the tutorial share it with your friends. Like the Facebook page for regular updates and YouTube channel for video tutorials.