In
Java, one interface can extends other interface.
Syntax
interface Interface2 extends
Interface1{
}
Example
interface Interface1{
int sum(int a, int b);
}
interface Interface2 extends Interface1{
int sum(int a, int b, int c);
}
Any
class implementing the interface “Interface2” must provide the
implementation for both the methods
int sum(int a, int b);
int sum(int a, int b, int c);
class Sum implements Interface2{ public int sum(int a, int b, int c){ return (a+b+c); } }
When
you tries to compile the above program, compiler throws the below
error.
Sum.java:1: error: Sum is not abstract and does not override abstract method sum(int,int) in Interface1 class Sum implements Interface2{ ^ 1 error
To
make the program compiles fine, implement both the methods.
class Sum implements Interface2{ public int sum(int a, int b, int c){ return (a+b+c); } public int sum(int a, int b){ return (a+b); } }
Some
Points to Remember
1. Can an Interface abstract ?
Yes, but no point in putting
abstract modifier for the interface, since all the method in
interface are abstract by default
Example
abstract interface Area{
double
PI=3.1428;
double
getArea(double r);
}
2.
Can an interface extend more than one interface ?
A
single interface can extend any number of other interfaces.
Example
Example
interface Interface1{ int sum(int a, int b); } interface Interface2 extends Interface1{ int sum(int a, int b, int c); }
interface Interface3 extends Interface1, Interface2{ }
3.
Is empty interface like below are valid ?
Interface
Interface1{
}
Yes,
It is Perfectly valid. Interfaces without methods and fields are called marker interfaces. Serializable, Cloneable and Remote interfaces are marker interfaces.
Implement more than one interface Class inside interface Home
No comments:
Post a Comment