Monday 17 February 2014

Interface as Reference Types

Interfaces can be used as Reference types. If you define a reference variable whose type is an interface, any object you assign to it must be an instance of a class that implements the interface.
interface Circle{
  double PI = 3.1428;
  double getArea(int r);
}

class MyCircle implements Circle{
  public double getArea(int r){
    return (Circle.PI * r * r);
  }

  public double getPerimeter(int r){
    return (Circle.PI * 2 * r);
  }

  public static void main(String args[]){
    Circle circle1 = new MyCircle();
    System.out.println("Area of the circle is " +circle1.getArea(10));
  }
}
Output
Area of the circle is 314.28

By Assigning an object to the interface type, the reference variable “circle1” call only the methods declared in the interface. Trying to call the methods which are not declared in the interface cause the compiler error.

Example

class MyCircle implements Circle{
  public double getArea(int r){
    return (Circle.PI * r * r);
  }

  public double getPerimeter(int r){
    return (Circle.PI * 2 * r);
  }

  public static void main(String args[]){
    Circle circle1 = new MyCircle();
    circle1.getPerimeter(10);
  }
}


Above program, tries to call the getPerimeter(), which is not declared in the interface Circle. So trying to call this method throws below compiler error.

MyCircle.java:12: error: cannot find symbol
circle1.getPerimeter(10);
^
symbol: method getPerimeter(int)
location: variable circle1 of type Circle
1 error

Interfaces                                                 Implement more than one interface                                                 Home

No comments:

Post a Comment