I have two programs one implemented using interfaces and the other implemented using only classes -
I've read that the advantage of using an interface is that it can provide it's own implementation of methods of super class but that can be done using abstract classes or method overriding. What purpose does interfaces serve?
In what kind of hierarchy and situation using interface will be most beneficial?
INTERFACE
interface Shape
{
void area(int x, int y);
}
class Rectangle implements Shape
{
@Override
public void area(int length, int breadth)
{
System.out.println(length*breadth);
}
}
class Triangle implements Shape
{
@Override
public void area(int base, int height)
{
System.out.println(base*height);
}
}
public class ShapeUsingInterface
{
public static void main(String X[])
{
Rectangle r = new Rectangle();
Triangle t = new Triangle();
r.area(5, 4);
t.area(6, 3);
}
}
CLASS
class Shape
{
void Area(int x, int y)
{
System.out.println(x*y);
}
}
class Rectangle extends Shape
{
}
class Triangle extends Shape
{
@Override
void Area(int base, int height)
{
System.out.println((0.5)*base*height);
}
}
public class CalculateArea
{
public static void main(String X[])
{
Rectangle r = new Rectangle();
Triangle t = new Triangle();
r.Area(4, 5);
t.Area(6, 8);
}
}