Java provides an alternate approach known as interfaces to support the concept of multiple inheritance. Although a Java class cannot be a subclass of more than one super class, it can implement more than one interface, thereby enabling the user to create classes that build upon other classes without the problems created by multiple inheritance. Defining an Interfaces An interface is basically a kind of class. Like classes, interfaces contain methods and variables but with a major difference. The difference is that interfaces define only abstract methods and final fields.This means that interface do not specify any code to implement these methods and data fields contain only the constants. Therefore it is the responsibility of the class that implements an interface to define the code for implementation of these methods. An interface is a contract for what a class can do, without saying anything about how the class will do it. Interfaces are like a 100-percent abstract super class that defines the methods a subclass must support, but not how they must be supported. The syntax for defining an interface is as follows: Here interface is the keyword and Interface Name is any valid Java variable. Variables are declared as follows: Static final type variableName=value; All variables are declared as constants. Method declaration will contain only a list of methods without any body statements. Return-type methodName1 (Parameter list);
Declaring an Interface The rules to be considered while declaring an interface are 1. All interface methods are implicitly public and abstract. No need to actually type the public or abstract modifiers in the method declaration, but the method is still always public and abstract. An example for an interface is: public interface Shape { Extending interfaces public class Square extends Rectangle { Implementing interfaces Interfaces are used as “super classes” whose properties are inherited by classes. It is therefore necessary to create a class that inherits the given interface. interface Area { public class Rectangle implements Area { class InterfaceTest { } Any number of dissimilar classes can implement an interface. Note that if a class implements an interface does not implement all the methods of the interface, then the class becomes an abstract class and cannot be instantiated. |