![]() SwapTemp.java (Uses a temporary variable to swap the two values) public class SwapTemp implements ISwap An example demonstrating this use of interfaces is as shown below: Interfaces enables developers of classes to implement the methods using different algorithms of their choice.Ī user can use any of the available implementations by simply creating an object of that class. The real power of interfaces lies in separating the specification of methods from their implementation in a class. The output of the above program is Method implemented successfully. In the above example nested interface is IA. A fully qualified reference must be used (as in A.IA) to reference a nested interface outside the enclosing class or interface. Let’s look at an example of how to create and use a nested interface: A nested interface can be declared as public, private or protected. In the above example, Person class provides implementation for methods in the interface IMovable.Īn interface which is declared inside a class or another interface is called a nested interface or a member interface. Let’s consider two classes Animal and Person which implements the interface IMovable defined above:Ībstract class Animal implements IMovable Implementations of methods in the interface The methods of the interface must be declared as public in the class. Syntax for implementing an interface is as follows: Otherwise, if a class provides implementation for only some methods (partial implementation) then the class should be made abstract. It is mandatory for a class to implement (provide body) all the methods available in an interface. This process of a class implementing the methods in an interface is known as implementing interfaces. ![]() The methods declared in an interface definition must be implemented by the class which inherits that interface. In the above example, IMovable is the interface name which contains three methods crawl, run and jump. All methods declared inside an interface are by default abstract and both variables as well as methods are implicitly public.Īn example for Java interface is as follows: ![]() They end with a semi-colon after the parameters list.Īll variables declared inside an interface are by default final and static. The syntax for defining an interface is as follows:Īccess specifier before interface keyword can be public or default (no specifier). All the methods inside an interface definition does not contain any body. The definition of an interface is very much similar to the definition of a class. ![]()
0 Comments
Leave a Reply. |
AuthorWrite something about yourself. No need to be fancy, just an overview. ArchivesCategories |