PREV NEXT
Java Interface:
Interface is similar to that of a class except that it can contain only constants and abstract methods.
Example:
1 2 3 4 5 |
interface A{ void method1(); //all methods are abstract void method2(); void method3(); } |
- Since the methods in interface are implicitly abstract, the keyword ‘abstract’ need not have to be prefixed.
- Interface cannot be instantiated. It should only be implemented and used by the class implementing it.
- A class can implement an interface using ‘implements’ keyword.
Syntax:
class <class_name> implements <interface_name>
{ // Implementation } |
- A class can implement more than one interface.
Example:
1 2 3 4 5 6 7 |
Interface A { …} Interface B { ..} Class Example implements A,B{ //statement } |
- All the fields of an interface are implicitly public,static,final and all the methods are implicitly public, abstract.
- A class which implements an interface has to implement all the methods declared in the interface otherwise it has to be declared as abstract.
- An abstract class can implement an interface but it is not necessary to implement all the methods of the interface.
- An interface can inherit another interface by using ‘extends’ keyword.
- When a class implements an interface that inherits another interface, then the class has to implement the methods of all the interfaces associated with the interface inheritance.
Example:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 |
interface A { Void method1(); Void method2(); } interface B extends A { Void method3(); } class New implements A, B { { method1() {//define...} method2() {//define....} method3() {//define....} } |
Example program using interface:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 |
interface Remote { Int Remote_Version =2.1.1; void start(); void stop(); } class SplitAC implements Remote { void start(){ //code to start the SplitAC } void stop(){ //code to stop the SplitAC } } Class WindowAC implements Remote { void start() { //code to start the WindowAC } void stop() { //code to stop the WindowAC } } |