Interface (Java)

Last updated

An interface in the Java programming language is an abstract type that is used to declare a behavior that classes must implement. They are similar to protocols. Interfaces are declared using the interface keyword, and may only contain method signature and constant declarations (variable declarations that are declared to be both static and final ). All methods of an Interface do not contain implementation (method bodies) as of all versions below Java 8. Starting with Java 8, default [1] :99 and static [1] :7 methods may have implementation in the interface definition. [2] Then, in Java 9, private and private static methods were added. At present, a Java interface can have up to six different types.

Contents

Interfaces cannot be instantiated, but rather are implemented. A class that implements an interface must implement all of the non-default methods described in the interface, or be an abstract class. Object references in Java may be specified to be of an interface type; in each case, they must either be null, or be bound to an object that implements the interface.

One benefit of using interfaces is that they simulate multiple inheritance. All classes in Java must have exactly one base class, the only exception being java.lang.Object (the root class of the Java type system); multiple inheritance of classes is not allowed. However, an interface may inherit multiple interfaces and a class may implement multiple interfaces.

Overview

Interfaces are used to encode similarities which the classes of various types share, but do not necessarily constitute a class relationship. For instance, a human and a parrot can both whistle; however, it would not make sense to represent Humans and Parrots as subclasses of a Whistler class. Rather they most likely be subclasses of an Animal class (likely with intermediate classes), but both would implement the Whistler interface.

Another use of interfaces is being able to use an object without knowing its type of class, but rather only that it implements a certain interface. For instance, if one were annoyed by a whistling noise, one may not know whether it is a human or a parrot, because all that could be determined is that a whistler is whistling. The call whistler.whistle() will call the implemented method whistle of object whistler no matter what class it has, provided it implements Whistler. In a more practical example, a sorting algorithm may expect an object of type Comparable . Thus, without knowing the specific type, it knows that objects of that type can somehow be sorted.

For example:

interfaceBounceable{doublepi=3.1415;voidsetBounce();// Note the semicolon// Interface methods are public, abstract and never final. // Think of them as prototypes only; no implementations are allowed.}

An interface:

Usage

Defining an interface

Interfaces are defined with the following syntax (compare to Java's class definition):

[visibility] interface InterfaceName [extends other interfaces] {         constant declarationsabstract method declarations static method declarations }

Example: public interface Interface1 extends Interface2;

The body of the interface contains abstract methods, but since all methods in an interface are, by definition, abstract, the abstract keyword is not required. Since the interface specifies a set of exposed behaviors, all methods are implicitly public.

Thus, a simple interface may be

publicinterfacePredator{booleanchasePrey(Preyp);voideatPrey(Preyp);}

The member type declarations in an interface are implicitly static, final and public, but otherwise they can be any type of class or interface. [3]

Implementing interfaces in a class

The syntax for implementing an interface uses this formula:

... implements InterfaceName[, another interface, another, ...] ...

Classes may implement an interface. For example:

publicclassLionimplementsPredator{@OverridepublicbooleanchasePrey(Preyp){// Programming to chase prey p (specifically for a lion)}@OverridepublicvoideatPrey(Preyp){// Programming to eat prey p (specifically for a lion)}}

If a class implements an interface and does not implement all its methods, it must be marked as abstract. If a class is abstract, one of its subclasses is expected to implement its unimplemented methods, though if any of the abstract class' subclasses do not implement all interface methods, the subclass itself must be marked again as abstract.

Classes can implement multiple interfaces:

publicclassFrogimplementsPredator,Prey{...}

Interfaces can share common class methods:

classAnimalimplementsLikesFood,LikesWater{booleanlikes(){returntrue;}}

However a given class cannot implement the same or a similar interface multiple times:

classAnimalimplementsShares<Boolean>,Shares<Integer>...// Error: repeated interface

Interfaces are commonly used in the Java language for callbacks, [4] as Java does not allow multiple inheritance of classes, nor does it allow the passing of methods (procedures) as arguments. Therefore, in order to pass a method as a parameter to a target method, current practice is to define and pass a reference to an interface as a means of supplying the signature and address of the parameter method to the target method rather than defining multiple variants of the target method to accommodate each possible calling class.

Subinterfaces

Interfaces can extend several other interfaces, using the same formula as described below. For example,

publicinterfaceVenomousPredatorextendsPredator,Venomous{// Interface body}

is legal and defines a subinterface. It allows multiple inheritance, unlike classes. Predator and Venomous may possibly define or inherit methods with the same signature, say kill(Prey p). When a class implements VenomousPredator it will implement both methods simultaneously.

Examples

Some common Java interfaces are:

See also

Citations

  1. 1 2 3 4 Bloch 2018.
  2. "Default Methods". Archived from the original on 2017-05-23. Retrieved 2014-06-30.
  3. "The Java Language Specification".
  4. Mitchell, John D. (June 1, 1996). "Java Tip 10: Implement callback routines in Java". JavaWorld . Retrieved 2020-07-14.

Related Research Articles

In object-oriented programming, a class is an extensible program-code-template for creating objects, providing initial values for state and implementations of behavior. In many languages, the class name is used as the name for the class, the name for the default constructor of the class, and as the type of objects generated by instantiating the class; these distinct concepts are easily conflated. Although, to the point of conflation, one could argue that is a feature inherent in a language because of its polymorphic nature and why these languages are so powerful, dynamic and adaptable for use compared to languages without polymorphism present. Thus they can model dynamic systems more easily.

Multiple inheritance is a feature of some object-oriented computer programming languages in which an object or class can inherit features from more than one parent object or parent class. It is distinct from single inheritance, where an object or class may only inherit from one particular object or class.

In class-based programming, the factory method pattern is a creational pattern that uses factory methods to deal with the problem of creating objects without having to specify the exact class of the object that will be created. This is done by creating objects by calling a factory method—either specified in an interface and implemented by child classes, or implemented in a base class and optionally overridden by derived classes—rather than by calling a constructor.

A method in object-oriented programming (OOP) is a procedure associated with an object, and generally also a message. An object consists of state data and behavior; these compose an interface, which specifies how the object may be used. A method is a behavior of an object parametrized by a user.

In object-oriented programming languages, a mixin is a class that contains methods for use by other classes without having to be the parent class of those other classes. How those other classes gain access to the mixin's methods depends on the language. Mixins are sometimes described as being "included" rather than "inherited".

The fragile base class problem is a fundamental architectural problem of object-oriented programming systems where base classes (superclasses) are considered "fragile" because seemingly safe modifications to a base class, when inherited by the derived classes, may cause the derived classes to malfunction. The programmer cannot determine whether a base class change is safe simply by examining in isolation the methods of the base class.

In object-oriented programming, in languages such as C++, and Object Pascal, a virtual function or virtual method is an inheritable and overridable function or method for which dynamic dispatch is facilitated. This concept is an important part of the (runtime) polymorphism portion of object-oriented programming (OOP). In short, a virtual function defines a target function to be executed, but the target might not be known at compile time.

The marker interface pattern is a design pattern in computer science, used with languages that provide run-time type information about objects. It provides a means to associate metadata with a class where the language does not have explicit support for such metadata.

This article compares two programming languages: C# with Java. While the focus of this article is mainly the languages and their features, such a comparison will necessarily also consider some features of platforms and libraries. For a more detailed comparison of the platforms, see Comparison of the Java and .NET platforms.

<span class="mw-page-title-main">Java syntax</span> Set of rules defining correctly structured program

The syntax of Java is the set of rules defining how a Java program is written and interpreted.

Many programming language type systems support subtyping. For instance, if the type Cat is a subtype of Animal, then an expression of type Cat should be substitutable wherever an expression of type Animal is used.

In object-oriented programming, inheritance is the mechanism of basing an object or class upon another object or class, retaining similar implementation. Also defined as deriving new classes from existing ones such as super class or base class and then forming them into a hierarchy of classes. In most class-based object-oriented languages like C++, an object created through inheritance, a "child object", acquires all the properties and behaviors of the "parent object", with the exception of: constructors, destructors, overloaded operators and friend functions of the base class. Inheritance allows programmers to create classes that are built upon existing classes, to specify a new implementation while maintaining the same behaviors, to reuse code and to independently extend original software via public classes and interfaces. The relationships of objects or classes through inheritance give rise to a directed acyclic graph.

In programming languages, an abstract type is a type in a nominative type system that cannot be instantiated directly; a type that is not abstract – which can be instantiated – is called a concrete type. Every instance of an abstract type is an instance of some concrete subtype. Abstract types are also known as existential types.

In computer programming, a trait is a concept used in programming languages which represents a set of methods that can be used to extend the functionality of a class.

In the Java computer programming language, an annotation is a form of syntactic metadata that can be added to Java source code. Classes, methods, variables, parameters and Java packages may be annotated. Like Javadoc tags, Java annotations can be read from source files. Unlike Javadoc tags, Java annotations can also be embedded in and read from Java class files generated by the Java compiler. This allows annotations to be retained by the Java virtual machine at run-time and read via reflection. It is possible to create meta-annotations out of the existing ones in Java.

<span class="mw-page-title-main">Java collections framework</span> Collections in Java

The Java collections framework is a set of classes and interfaces that implement commonly reusable collection data structures.

Generics are a facility of generic programming that were added to the Java programming language in 2004 within version J2SE 5.0. They were designed to extend Java's type system to allow "a type or method to operate on objects of various types while providing compile-time type safety". The aspect compile-time type safety was not fully achieved, since it was shown in 2016 that it is not guaranteed in all cases.

In software engineering, a fluent interface is an object-oriented API whose design relies extensively on method chaining. Its goal is to increase code legibility by creating a domain-specific language (DSL). The term was coined in 2005 by Eric Evans and Martin Fowler.

<span class="mw-page-title-main">Composition over inheritance</span> Software design pattern

Composition over inheritance in object-oriented programming (OOP) is the principle that classes should favor polymorphic behavior and code reuse by their composition over inheritance from a base or parent class. Ideally all reuse can be achieved by assembling existing components, but in practice inheritance is often needed to make new ones. Therefore inheritance and object composition typically work hand-in-hand, as discussed in the book Design Patterns (1994).

References