Monday 17 February 2014

Class can implement more than one interface

In Java, a class can implement more than one interface.

Syntax
    class ClassName implements Interface1, Interface2{

    }

Example
interface Area{
  double getArea(double r);
}
 

interface Perimeter{
  double getPerimeter(double r);
}

class MyCircle implements Area, Perimeter{
  final double PI=3.1428;
  
  public double getArea(double r){
    return (PI * r * r);
  }

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

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

Output
314.28
62.855999999999995
Some points to Remember

1. If a class implementing multiple interfaces, and more than one interface has same variable definition, then using the variable directly causes ambiguity to the compiler
interface Perimeter{
  double PI=3.14;
  double getPerimeter(double r);
}

interface Area{
  double PI=3.1428;
  double getArea(double r);
}

class MyCircle implements Area, Perimeter{
  public double getArea(double r){
    return (PI * r * r);
  }

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

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

When you tries to compile the above program, compiler throws the below error
MyCircle.java:3: error: reference to PI is ambiguous, both variable PI in Area and variable PI in Perimeter match
return (PI * r * r);
^

MyCircle.java:7: error: reference to PI is ambiguous, both variable PI in Area and variable PI in Perimeter match
return (PI * 2 * r);

To make the program run, be specific about the variable PI you are going to use.
class MyCircle implements Area, Perimeter{
  public double getArea(double r){
    return (Area.PI * r * r);
  }

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

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

Output
314.28
62.800000000000004

2. Can interface be final?
No, Interfaces can't be final. A final class is not extendable. If you make interface as final, there is no use of it. So it is illegal in java.

final interface Area{
  double PI=3.1428;
  double getArea(double r);
}

When you tries to compile the above class, compiler throws the below error

Area.java:1: error: illegal combination of modifiers: interface and final
final interface Area{
^
1 error




Interface as reference types                                                 Extending interfaces                                                 Home

No comments:

Post a Comment