Interface Illustrated

  • 0
     Via interfaces, one can specify what a class must do, but not how it should do it. An interface is just like a class and is defined in almost same way.

     access interface_name
     {
          return_type method_name1(parameter_list);
          return_type method_name2(parameter_list);

          type final_var_name = value;
     }
    When no access specifier is given, access is understood to be default. Default access restricts the use of interface to the current package only.
     All variable declared in an interface are static and final. They can't be changed later. So, they must be provided value in the beginning. All the methods are public implicitly. Here is an implementation of an interface named Figure which is to be3 named Figure.java.

package InterfaceIllustration;
interface Figure
{
 int area(int side1, int side2);
 int perimeter(int...side);
}
As you can see, we have two methods in the Figure interface, first one is area() that accepts two integer parameters and second is perimeter() that receives variable number of parameters. Next source file is to be named ActTri.java and it implements Figure interface.
package InterfaceIllustration;

class Tringle implements Figure
{
 public int area(int height, int base)
 {
  return ((height*base)/2);
 }
 
 public int perimeter(int...side)
 {
  int peri=0;
  for(int i:side)
   peri = peri + i;
  
  return peri;
 }
}
class ActTri
{
 public static void main(String args[])
 {
  //First with Tringle Reference
  Tringle t = new Tringle();
  System.out.println("Area of Tringle with side height 4 and base 2 is " + t.area(4,2));
  System.out.println("Perimeter of Tringle with side 4,2,1 is " + t.perimeter(4,2,1));
  
  System.out.println();
  //Now with Figure Reference;
  Figure f;
  f = t;
  System.out.println("Area of Tringle with side height 6 and base 4 is " + f.area(4,6));
  System.out.println("Perimeter of Tringle with side 6,4,2 is " + f.perimeter(6,4,2));
 }
}
As you can see, class Triangle implements its own versions of area() and perimeter() methods. Here, first I have created an object of class Triangle and have tried to call the methods area() and perimeter() with it. Next time, I have created an reference to Interface Figure itself. Later, this interface is made to pint to object of class Triangle. Now, via this, I can also call the area(0 and perimeter() methods of class Triangle. Here is the sample output that I got.
Area of Tringle with side height 4 and base 2 is 4
Perimeter of Tringle with side 4,2,1 is 7

Area of Tringle with side height 6 and base 4 is 12
Perimeter of Tringle with side 6,4,2 is 12

No comments:

Post a Comment