Java how to implement interface

Implementing an Interface

To declare a class that implements an interface, you include an implements clause in the class declaration. Your class can implement more than one interface, so the implements keyword is followed by a comma-separated list of the interfaces implemented by the class. By convention, the implements clause follows the extends clause, if there is one.

A Sample Interface, Relatable

Consider an interface that defines how to compare the size of objects.

public interface Relatable < // this (object calling isLargerThan) // and other must be instances of // the same class returns 1, 0, -1 // if this is greater than, // equal to, or less than other public int isLargerThan(Relatable other); >

If you want to be able to compare the size of similar objects, no matter what they are, the class that instantiates them should implement Relatable .

Any class can implement Relatable if there is some way to compare the relative «size» of objects instantiated from the class. For strings, it could be number of characters; for books, it could be number of pages; for students, it could be weight; and so forth. For planar geometric objects, area would be a good choice (see the RectanglePlus class that follows), while volume would work for three-dimensional geometric objects. All such classes can implement the isLargerThan() method.

If you know that a class implements Relatable , then you know that you can compare the size of the objects instantiated from that class.

Читайте также:  Готовый программный код python

Implementing the Relatable Interface

Here is the Rectangle class that was presented in the Creating Objects section, rewritten to implement Relatable .

public class RectanglePlus implements Relatable < public int width = 0; public int height = 0; public Point origin; // four constructors public RectanglePlus() < origin = new Point(0, 0); >public RectanglePlus(Point p) < origin = p; >public RectanglePlus(int w, int h) < origin = new Point(0, 0); width = w; height = h; >public RectanglePlus(Point p, int w, int h) < origin = p; width = w; height = h; >// a method for moving the rectangle public void move(int x, int y) < origin.x = x; origin.y = y; >// a method for computing // the area of the rectangle public int getArea() < return width * height; >// a method required to implement // the Relatable interface public int isLargerThan(Relatable other) < RectanglePlus otherRect = (RectanglePlus)other; if (this.getArea() < otherRect.getArea()) return -1; else if (this.getArea() >otherRect.getArea()) return 1; else return 0; > >

Because RectanglePlus implements Relatable , the size of any two RectanglePlus objects can be compared.

Note: The isLargerThan method, as defined in the Relatable interface, takes an object of type Relatable . The line of code, shown in bold in the previous example, casts other to a RectanglePlus instance. Type casting tells the compiler what the object really is. Invoking getArea directly on the other instance ( other.getArea() ) would fail to compile because the compiler does not understand that other is actually an instance of RectanglePlus .

Источник

Interfaces

There are a number of situations in software engineering when it is important for disparate groups of programmers to agree to a «contract» that spells out how their software interacts. Each group should be able to write their code without any knowledge of how the other group’s code is written. Generally speaking, interfaces are such contracts.

For example, imagine a futuristic society where computer-controlled robotic cars transport passengers through city streets without a human operator. Automobile manufacturers write software (Java, of course) that operates the automobile—stop, start, accelerate, turn left, and so forth. Another industrial group, electronic guidance instrument manufacturers, make computer systems that receive GPS (Global Positioning System) position data and wireless transmission of traffic conditions and use that information to drive the car.

The auto manufacturers must publish an industry-standard interface that spells out in detail what methods can be invoked to make the car move (any car, from any manufacturer). The guidance manufacturers can then write software that invokes the methods described in the interface to command the car. Neither industrial group needs to know how the other group’s software is implemented. In fact, each group considers its software highly proprietary and reserves the right to modify it at any time, as long as it continues to adhere to the published interface.

Interfaces in Java

In the Java programming language, an interface is a reference type, similar to a class, that can contain only constants, method signatures, default methods, static methods, and nested types. Method bodies exist only for default methods and static methods. Interfaces cannot be instantiated—they can only be implemented by classes or extended by other interfaces. Extension is discussed later in this lesson.

Defining an interface is similar to creating a new class:

public interface OperateCar < // constant declarations, if any // method signatures // An enum with values RIGHT, LEFT int turn(Direction direction, double radius, double startSpeed, double endSpeed); int changeLanes(Direction direction, double startSpeed, double endSpeed); int signalTurn(Direction direction, boolean signalOn); int getRadarFront(double distanceToCar, double speedOfCar); int getRadarRear(double distanceToCar, double speedOfCar); . // more method signatures >

Note that the method signatures have no braces and are terminated with a semicolon.

To use an interface, you write a class that implements the interface. When an instantiable class implements an interface, it provides a method body for each of the methods declared in the interface. For example,

public class OperateBMW760i implements OperateCar < // the OperateCar method signatures, with implementation -- // for example: public int signalTurn(Direction direction, boolean signalOn) < // code to turn BMW's LEFT turn indicator lights on // code to turn BMW's LEFT turn indicator lights off // code to turn BMW's RIGHT turn indicator lights on // code to turn BMW's RIGHT turn indicator lights off >// other members, as needed -- for example, helper classes not // visible to clients of the interface >

In the robotic car example above, it is the automobile manufacturers who will implement the interface. Chevrolet’s implementation will be substantially different from that of Toyota, of course, but both manufacturers will adhere to the same interface. The guidance manufacturers, who are the clients of the interface, will build systems that use GPS data on a car’s location, digital street maps, and traffic data to drive the car. In so doing, the guidance systems will invoke the interface methods: turn, change lanes, brake, accelerate, and so forth.

Interfaces as APIs

The robotic car example shows an interface being used as an industry standard Application Programming Interface (API). APIs are also common in commercial software products. Typically, a company sells a software package that contains complex methods that another company wants to use in its own software product. An example would be a package of digital image processing methods that are sold to companies making end-user graphics programs. The image processing company writes its classes to implement an interface, which it makes public to its customers. The graphics company then invokes the image processing methods using the signatures and return types defined in the interface. While the image processing company’s API is made public (to its customers), its implementation of the API is kept as a closely guarded secret—in fact, it may revise the implementation at a later date as long as it continues to implement the original interface that its customers have relied on.

Источник

Java Interfaces Tutorial

In this Java tutorial we learn about interfaces that, like abstract classes, doesn’t provide implementations for their members.

We discuss how to define and implement one or more interfaces, how to create a default fallback interface method, and how to use static, private and private static interface methods.

Lastly, we discuss interface inheritance by extending interfaces.

What is an interface

An interface is very similar to an abstract class , the class members aren’t implemented.

If you remember from our tutorial on composition , we spoke about favouring a has-a relationship over an is-a relationship. To recap quickly:

  • Inheritance can be abused, which may lead to a large, fragile hierarchy of classes.
  • Inheritance makes our classes tightly coupled and dependent on each other. We want them to be as loosely coupled as possible.

Interfaces allow us to have easy has-a relationships between classes. Instead of defining a class for each relationship, we define interfaces.

Even though an interface has nothing to do with inheritance, it does allow for polymorphic behavior in a similar way.

How to define an interface in Java

Interfaces are defined the same way as classes, except we use the interface keyword instead of the class keyword.

Interface methods aren’t implemented. We don’t add code blocks to methods, although they can contain parameters. Interfaces may also contain initialized constants (final variables).

  A few things should be noted about interfaces and their members.
  • Even though interface methods are abstract, they are not marked as such.
  • Interface methods are implicitly public and interface properties are implicitly public static final .
    • We don’t have to specify the access modifier inside interfaces, but it’s good practice to do so.

    Interfaces aren’t inherited, but rather implemented. We implement an interface with the implements keyword.

    Источник

Оцените статью