Interfaces have another very important role in the Java programming language. Interfaces are not part of the class hierarchy, although they work in combination with classes. The Java programming language does not permit multiple inheritance (inheritance is discussed later in this lesson), but interfaces provide an alternative.

Using interface, you can specify what a class must do, but not how it does it.

java does not have multiple inheritances

Inheritance gives us two things:

  • Code reuse
  • Ability to represent the object polymorphically.

Interface supports the concept of multiple inheritance

  • An interface specifies a list of one or more methods, giving only their signatures, but no code
  • A class implements an interface if it supplies code for all methods of that interface

Ex:

public interface Stack{

public Boolean isEmpty();

}

Class myStacks implements Stack{

IsEmpty(S);

Return(top<0);

}

An interface can be sub-interfaced from other interfaces ,sub-interfaced will inherit all members of superinterface:

Ex:

Interface class2 extends class1

{

body of class2

}

Classes Interface
  • A class can extend only one class
  • A class can implement any number of interfaces
  • A class have fields
  • An interface cannot have fields
  • A class defines its own constructors (or it gets a default constructor).
  • An interface has no constructors
  • A concrete class has all its methods defined. An abstract class usually has one or more abstract methods
  • All methods declared in an interface are abstract
  • Every class is a part of a hierarchy of classes with object at the top
  • An interface may belong to a small hierarchy of interfaces, but this is not as common.

Advantages of Interfaces:

  • It provides a standard set of methods for a group of classes.
  • Objects of these classes can be accessed by the standard set of methods without considering about their location in hierarchy.
  • Support selective multiple inheritance.

 

Advertisements