The Interfaces In JAVA (Official Website documentation translation), interfaces
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 shocould be able to write their code without any knowledge of how the other group's code is written. generally speaking,InterfacesAre such contracts.
In many cases of software engineering, it is important for a group or programmer to agree on a contract (a contract is used to explain how the software interacts. With the help of the contract, each group does not have to know how to write code for other groups when writing code. Generally, such a contract is performed by an interface.
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.
For example, imagine that in the near future, computer-controlled robot cars will carry passengers across city streets, while cars will be self-driving. The software written in JAVA for automobile manufacturing is used to operate automobiles-stop, start, accelerate, and turn left. Another Industrial Group electronic guidance instrument manufacturer uses a computer system to receive wireless transmission data of GPS data and traffic conditions, and uses the received data to drive a 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 knowHowThe 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.
The manufacturer of the vehicle must publish industry-standard interfaces, elaborate on the calling methods to move the vehicle, and then instruct the manufacturer to call the methods described in the interface to control the vehicle, the Industrial Group does not need to know how the software of other groups is implemented. In fact, each group thinks they are highly proprietary to the software and can modify the software at any time, provided that they follow the released interface specifications.
Interfaces in Java
In the Java programming language,InterfaceIs a reference type, similar to a class, that can containOnlyConstants, 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 beImplementedBy classes orExtendedBy other interfaces. Extension is discussed later in this lesson.
In JAVA, interfaces and classes are similar and are reference types. An interface can only contain methods, default methods, static methods, and nested methods. Method topics can only exist in the form of default and static methods. An interface cannot be instantiated. It can only be implemented by a class or inherited by other interfaces. The details will be discussed later.
Defining an interface is similar to creating a new class:
Defining a combination is very similar to creating a class:
1 public interface OperateCar { 2 3 // constant declarations, if any 4 5 // method signatures 6 7 // An enum with values RIGHT, LEFT 8 int turn(Direction direction, double radius, double startSpeed, double endSpeed); 9 10 int changeLanes(Direction direction, double startSpeed, double endSpeed);11 12 int signalTurn(Direction direction, boolean signalOn);13 14 int getRadarFront(double distanceToCar, double speedOfCar);15 16 int getRadarRear(double distanceToCar,17 double speedOfCar);......18 // more method signatures19 }
Note that the method signatures have no braces and are terminated with a semicolon.
To use an interface, you write a class thatImplementsThe interface. When an instantiable class implements an interface, it provides a method body for each of the methods declared in the interface. For example,
Note: The method does not contain () and ends with a semicolon.
To use an interface, you only need to write a class implementation interface. When a class implements an interface, it must implement each method in the interface description. For example:
1 public class OperateBMW760i implements OperateCar { 2 3 // the OperateCar method signatures, with implementation -- 4 // for example: 5 int signalTurn(Direction direction, boolean signalOn) { 6 // code to turn BMW's LEFT turn indicator lights on 7 // code to turn BMW's LEFT turn indicator lights off 8 // code to turn BMW's RIGHT turn indicator lights on 9 // code to turn BMW's RIGHT turn indicator lights off10 }11 12 // other members, as needed -- for example, helper classes not13 // visible to clients of the interface14 }
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.
The preceding example describes how to implement an interface for a self-driving car. Xuefulai and Toyota may have different implementations, but they say they follow the same interface. As an interface client, the guiding manufacturer will build a system that uses GPS data, digital street maps, and traffic data of the vehicle location to drive the car. In this way, the system will call the interface methods such as turning, changing lanes, braking, and acceleration.
Interfaces as APIs
The robotic car example shows an interface being used as an industry standardApplication Programming Interface (API). APIs are also common in each cial 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 wocould 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 MERs. 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.
The example of self-driving cars shows that interfaces are used as industry-standard APIs. APIs is also common in commercial software products. Generally, some companies sell software packages that contain complex methods for other companies to use in their software products. There may be an example: a package that provides image processing methods is sold to an end-user graphics program company. Graphic Processing Companies write classes that implement public interfaces. Graphic companies call methods defined in interfaces and return the types defined in interfaces. For customers, the APIs of image processing companies are open and the implementation of APIS is private-in fact, image processing companies can modify API implementations in the future, as long as it continues to implement the interface on which the customer depends.
Define Defining an Interface
An interface declaration consists of modifiers, the keywordinterface
, The interface name, a comma-separated list of parent interfaces (if any), and the interface body. For example:
Interface declaration includes modifiers, interface keywords, interface names, list of parent interfaces separated by commas (,), and interface subjects. For example:
1 public interface GroupedInterface extends Interface1, Interface2, Interface3 { 2 3 // constant declarations 4 5 // base of natural logarithms 6 double E = 2.718282; 7 8 // method signatures 9 void doSomething(int i, double x);10 11 int doSomethingElse(String s);12 }
Thepublic
Access specifier indicates that the interface can be used by any class in any package. if you do not specify that the interface is public, then your interface is accessible only to classes defined in the same package as the interface.
An interface can extend other interfaces, just as a class subclass or extend another class. however, whereas a class can extend only one other class, an interface can extend any number of interfaces. the interface declaration between des a comma-separated list of all the interfaces that it extends.
The public modifier indicates that this interface can be used by classes in any package. If the public modifier is not specified, the interface can only be used by classes in the same package as this interface.
Interfaces can inherit other interfaces, just like subclasses or inherit other classes. However, a class can only inherit one class, and an interface can inherit multiple interfaces. The interface declaration contains a list of interfaces to be inherited separated by commas.
The Interface Body
The interface body can contain in abstract methods, default methods, and static methods. an abstract method within an interface is followed by a semicolon, but no braces (an abstract method does not contain an implementation ). default methods are defined withdefault
Modifier, and static methods withstatic
Keyword. All abstract, default, and static methods in an interface are implicitlypublic
, So you can omitpublic
Modifier.
In addition, an interface can contain in constant declarations. All constant values defined In an interface are implicitlypublic
,static
, Andfinal
. Once again, you can omit these modifiers.
The interface topic can contain abstract methods, default methods, and static methods. The abstract method in the interface is followed by a semicolon, but there is no parentheses (the abstract method does not include the method implementation). The default modifier is used for defining the default method. The static method uses the static keyword. All abstract methods, default methods, and static methods in the interface are public by default, so you can omit the public modifier.
In addition, the interface can contain constant declarations. All constants defined in the interface are public, static, and finale by default. You can omit these modifiers.
Implementing an Interface
To declare a class that implements an interface, you includeimplements
Clause in the class declaration. Your class can implement more than one interface, soimplements
Keyword is followed by a comma-separated list of the interfaces implemented by the class. By convention,implements
Clause followsextends
Clause, if there is one.
To declare a class that implements an interface, you only need to include an implements statement in the class declaration. Class can implement multiple interfaces, so
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 shocould implementRelatable
.
Any class can implementRelatable
If there is some way to compare the relative "size" of objects instantiated from the class. for strings, it cocould be number of characters; for books, it cocould be number of pages; for students, it cocould be weight; and so forth. for planar geometric objects, area wocould be a good choice (seeRectanglePlus
Class that follows), while volume wocould work for three-dimen1_geometric objects. All such classes can implementisLargerThan()
Method.
If you know that a class implementsRelatable
, Then you know that you can compare the size of the objects instantiated from that class.