Interfaces in Java

Interfaces in java are same like an abstract class, it does not attribute definition and all of its methods are abstract. An interface don’t have constructors and can’t be instantiated. ¬†From Java 8 onward non abstract methods can be included in the interface by using default keyword. These methods are known as default or extension methods. ¬†Following are the most important points about java interfaces.

  • An interface is treated as a special class in java. Each interface is compiled into a separate byte code file.
  • An interface contains only constants and abstract methods
  • You can’t create instance from an interface using new operator. It means you can use interface more or less same way as an abstract class
  • Java interfaces share the common behavior among the instances of objects
  • A class can implement more then one interfaces
  • To model strong relationship always use classes
  • To model a weak type relationship use interface
  • You can also use interfaces to circumvent single inheritance restriction if multiple inheritance is desired. In the case of multiple inheritance, you have to design one as a superclass, and others as interface

Interface Syntax

Example 1

Example 2 : Implementing Eidble Interface and Extending Animal class

Example 3 : Extending Abstract class and Implementing Edible Interface

Including Default Methods in Interface

Besides the abstract methods sqroot and absolute, the interface MathEx also defines the default methods sqrt abd abs. Concrete classes only have to implement the abstract methods sqroot and absolute. The default methods sqrt and abs can be used out of the box.

No Responses