Java tutorial interface introduction, Java tutorial interface Introduction
Interfaces Interface
In software engineering, it is very common to define how software from different development groups interact with each other in a "contract. Each group can develop its own code independently without knowing the code of another group. The interface in Java is such a "contract ".
For example, if there is a smart car in the future society, it can automatically carry passengers without manual operation. Auto manufacturers have developed software (Java, of course) to control such cars, such as stopping, starting, accelerating, and turning left. The manufacturer of electronic navigation instruments is responsible for developing computer systems that receive wireless GPS location data and traffic conditions, and applying such information to drive cars.
Automobile Manufacturers must publish the industrial standard interface, which must explain in detail which methods can be used to control automobile movements (This standard applies to any automobile and any manufacturer ). The navigation system manufacturer can use the various methods described in this interface to control vehicles. No industrial vendor needs to know how other vendors implement their software. In fact, as long as everyone strictly abides by the published interface, each vendor has a high degree of ownership of its own software and has the right to modify it at any time.
Interface in java
In java programming language, an interface is a reference type. It is similar to a class, so it can only contain constants and method signatures) and nested types (nested types ). The Interface must not contain the method body ). An Interface cannot be instantiated. It can only be implemented by other classes or inherited by other interfaces.
Defining an interface is similar to creating a new class:
Copy codeThe Code is as follows:
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
}
To use the interface above, you need to write a class to implement it. When an instantiated class implements an interface, it needs to provide specific code for all the methods declared by the interface (methods.
In the preceding example, the automobile manufacturer is the real-time provider of the interface. The methods implemented by Chevrolet are certainly different from Honda's methods, but they all follow the same interface. The navigation system manufacturer is the user of this interface. Their system will drive the car Based on GPS data, digital maps, and traffic conditions of the car. Therefore, this navigation system will involve the following methods (methods): Turning, cutting, braking, acceleration, and so on.
API
The example of automated vehicles shows the Application of interfaces in industrial standard Application interfaces (APIs). APIs are also common in commercial software. Generally, a software package released by a company contains a complex method (methods) that other companies want to apply to their own products ). For example, a software package containing a digital image processing method can be sold to a company that develops client image software. After the purchase, the company can apply the method defined by interface. While image processing companies disclose their APIs to all customers, the implementation of these Apis is highly confidential. In fact, as long as the original interface remains unchanged, the implementation methods of these APIs are likely to be overwritten in the future.
Interfaces and multi-Inheritance
In java programming language, interface also plays an important role. Although an Interface is used with a class, it is not part of the class hierarchy. The java programming language does not support multiple inheritance, but the interface provides an alternative.
In java, a class can only inherit from a single class, but it can implement multiple interfaces. Therefore, an object can have multiple types: The type of its own class, and the type of all interfaces It inherits. This means that if you declare a variable as an interface type, this variable can refer to any instance of the class that implements this interface. This section details how to use the interface type.
Define an interface
An interface is defined by the modifier, the keyword interface, the interface name, the parent interface (parent interfaces) separated by commas, and the interface body ).
Example:
Copy codeThe Code is as follows:
Public interface GroupedInterface extends Interface1, Interface2, Interface3 {
// Constant declarations
// Base of natural logarithms
Double E = 2.718282;
// Method signatures
Void doSomething (int I, double x );
Int doSomethingElse (String s );
}
Public specifies that this interface can be used by any class in any package. If you declare that this interface is public, it can only be used by classes in the same package.
An interface can inherit other interfaces, just as a class can inherit other classes. However, a class can only inherit one parent class, but an interface can inherit any number of interfaces.
Interface body)
The interface object contains the declaration of all methods it contains. Each declaration ends with a quotation mark, because the interface does not need to implement the method it declares. All methods in the interface are public by default, so the modifier public can be omitted.
The API can also declare constants. Similarly, the modifier public, static, and final of constants can be omitted.
Interface implementation
To declare a class to implement an interface, you need to use implements in the class declaration. Your class can implement multiple interfaces, so the implements keyword can follow multiple interface names separated by commas. For convenience, the implements keyword is mostly behind the extends keyword.
One API instance-Relatable
Relatable is an interface used to compare the sizes of two objects.
Copy codeThe Code is as follows:
Public interface Relatable {
// This (object calling isLargerThan)
// And other must be instances
// 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 compare the sizes of two similar objects, No matter what class the object belongs to, this class needs to implement the Relatable interface.
As long as there is a way to compare the relative size of the object, any class can implement the Relatable interface. For strings, the number of characters can be compared; for books, the number of pages can be compared; for students, the weight can be compared. Compared area is a good choice for plane geometric objects. for three-dimensional objects, it is necessary to compare the volume. All the above classes can implement the int isLargerThan () method.
If you know that a class implements the Relatable interface, you can compare the objects instantiated from this class.
Implementation of the Relatable Interface
The following is a triangle class that implements the Relatable interface.
Copy codeThe Code is as follows:
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;
}
}
Interface Type
When you define a new interface, you are actually defining a new reference type. You can use the interface name wherever you can use the data type name. If you define a reference variable of the interface type, the class of the object to which the variable points must implement the interface.
The following example shows a method for returning large objects in a pair of objects:
Copy codeThe Code is as follows:
Public Object findLargest (Object object1, Object object2 ){
Relatable obj1 = (Relatable) object1;
Relatable obj2 = (Relatable) object2;
If (obj1). isLargerThan (obj2)> 0)
Return object1;
Else
Return object2;
}
By converting data type object1 to Relatable, object obj1 can call the isLargerThan method.
Similarly, the following method can be used as long as the Relatable class is implemented.
Copy codeThe Code is as follows:
Public Object findSmallest (Object object1, Object object2 ){
Relatable obj1 = (Relatable) object1;
Relatable obj2 = (Relatable) object2;
If (obj1). isLargerThan (obj2) <0)
Return object1;
Else
Return object2;
}
Public boolean isEqual (Object object1, Object object2 ){
Relatable obj1 = (Relatable) object1;
Relatable obj2 = (Relatable) object2;
If (obj1). isLargerThan (obj2) = 0)
Return true;
Else
Return false;
}
These methods apply to any "Relatable" class, regardless of their inheritance relationships. Implements the Relatable class, which belongs to both the own (or parent class) type and the Relatable type. This gives them the advantages of multi-inheritance, because they can have both parent class and interface behavior.
Rewrite Interface
Suppose you have developed an interface named DoIt:
Copy codeThe Code is as follows:
Public interface DoIt {
Void doSomething (int I, double x );
Int doSomethingElse (String s );
}
Then, you want to add a new method in this interface, so the code becomes:
Copy codeThe Code is as follows:
Public interface DoIt {
Void doSomething (int I, double x );
Int doSomethingElse (String s );
Boolean didItWork (int I, double x, String s );
}
If you modify it, all classes that implement the old DoIt interface will encounter errors, because they do not implement this interface correctly. All programmers who use this interface will seriously protest against your modifications.
You need to estimate the needs of your interface users and complete the design of this interface from the very beginning. But this is often not possible. Another solution is to write another interface. For example, you can write a DoItPlus interface to inherit the original interface.
Copy codeThe Code is as follows:
Public interface DoItPlus extends DoIt {
Boolean didItWork (int I, double x, String s );
}
Now, you can choose to continue using the old interface DoIt or upgrade the new interface DoItPlus.
Summary
An interface is the communication protocol between two objects.
The declaration of an interface contains signatures of some methods, but they do not need to be implemented. It may also contain constants.
The class that implements an interface must implement all the methods declared by this interface.
You can use the interface name wherever the type name is used.
Oracle, compilation: @ philhu
Several tricks to prevent Java Vulnerabilities
Java Exception Handling
After a year, Java is moving in the right direction.
Seven common Java enumeration usage
Select Java or. NET