-2

What is the use of interface if it should be defined in the subclass implementing it? Also, to access an interface we need to create an object of that class.

import java.io.*;

Interface area
{ 
  compute();
}

Class rectangle implements area
{
  compute()
  {
    x*y;
  }
}

Class circle implements area
{
  compute()
  {
    x*y;
  }
}

Class test
{
  public static void main(String args[])
  {
   rectangle r=new rectangle();
   area ar;
   ar=r;
   ar.compute();
  }
}
Meraj al Maksud
  • 1,528
  • 2
  • 22
  • 36
joby george
  • 73
  • 1
  • 9
  • 4
    Does [this](https://stackoverflow.com/questions/383947/what-does-it-mean-to-program-to-an-interface) answer your question? – Sweeper Sep 22 '19 at 11:00
  • You dont have to care if its a circle or rectangle. As long as you know it's a area you can call the method compute(). You can look at it as if it were a contract. – Willem Sep 22 '19 at 11:01

1 Answers1

1

Interfaces are contracts that define behaviors that solid classes implement. Any implementing class of your Area interface should contain a compute implementation. Anyone writing methods that depend on the Area interface can ask for the computed area without knowing if the implementation is a Circle or a Square.

For example, if your compute method would return the area, you could have a print method.

void printArea(Area a){
    System.out.println(a.compute());
}

What does it mean to "program to an interface"?

Meraj al Maksud
  • 1,528
  • 2
  • 22
  • 36
Martin'sRun
  • 522
  • 3
  • 11