Java interface

xiaoxiao2021-04-01  207

Interfaces

In The Java Programming Language, An Interface Is Not a Class But A Set of Requirements for Classes That Want To Conform To The Interface (Directive Sets to implement a class of an interface).

Typically, the supplier of some service states: ". If your class conforms to a particular interface, then I'll perform the service" Let's look at a concrete example The sort method of the Arrays class promises to sort an array of objects,. But Under One Condition: The Objects Must Belong To Classes That Implement The Comparable Interface.

Here is what the comparable interface locks like:

Public Interface Comparable

{

Int CompareTo (Object Other);

}

This Means That Any Class That Implements The Comparable Interface Is Required To Have a Compareto Method, And The Method Must Take An Object Parameter And Return An Integer.

Note

AS of JDK 5.0, The Comparable Interface Has Been Enhanced To Be a Generic Type (JDK5.0, the Comparable interface has been enhanced to generics).

Public Interface Comparable

{

INT COMPARETO (T Other); // Parameter Has Type T

}

For Example, a class thing imports comparable Must Supply a method

INT COMPARETO (Employee Other)

You Can Still Use The "Raw" Comparable Type Without a Type Parameter, but the designer of the compareto method to the desired type.

All Methods of An Interface Are Automatically PUBLIC (the method in the interface is automatically published). For That Reason, IT IS Not Necessary To Supply The Keyword Public When Decilaning a Method In an Interface.

Of course, there is an additional requirement that the interface can not spell out: When calling x.compareTo (y), the compareTo method must actually be able to compare two objects and return an indication whether x or y is larger The method is supposed. to return a negative number if x is smaller than y, zero if they are equal, and a positive number otherwise.This particular interface has a single method. Some interfaces have more than one method. As you will see later, interfaces can also define constants (interfaces may define a constant). What is more important, however, is what interfaces can not supply. interfaces never have instance fields, and the methods are never implemented in the interface (the interface can not contain instance fields, and can not be implemented method) . Supplying instance fields and method implementations is the job of the classes that implement the interface (providing examples of domain and implementation is to achieve a certain kind of task interface). You can think of an interface as being similar to an abstract class with no Instance Fields (you can view the interface as an abstract class without instance). However, There Area Some Differences Between There Two Concepts-WE Look At Them Later in Some Detail.

Now Suppose We Want To Use The Sort Method of The Arrays Class To Sort An Array Of Employe Objects. The Employee Class Must Implement The Compailable Interface.

To make a class import an interface, you carry out two steps:

1. You Declare That Your Class Intends TO IMPLEMENT The GIVEN Interface.

2. You Supply Definitions for All Methods in the interface.

To Declare That A class imports an interface, use the importments keyword:

Class Employee IMPLEments Comparable

Of course, now the Employee class needs to supply the compareTo method. Let's suppose that we want to compare employees by their salary. Here is a compareTo method that returns -1 if the first employee's salary is less than the second employee's salary, 0 if THEY Are Equal, and 1 Otherwise.public Int Compareto (Object OtherObject)

{

Employee Other = (EMPLOYEE) OtherObject;

ife (Salary

IF (Salary> Other.salary) Return 1;

Return 0;

}

Caution

In the interface declaration, the compareTo method was not declared public because all methods in an interface are automatically public. However, when implementing the interface, you must declare the method as public (However, when implementing an interface, the method must be declared as public ). Otherwise, the compiler assumes That The Method Has Package Visibility-The Default for a class. The Compiler Complains That You Try To Supply A Weaker Access Privilege.

AS OF JDK 5.0, We can do a little better. We'll Decide to Implement The Comparable Interface Type Instead.

Class Employee IMPLEments Comparable

{

Public int compareto (EMPLOYEE OTHER)

{

ife (Salary

IF (Salary> Other.salary) Return 1;

Return 0;

}

.

}

Note That the unsightly cast of the object parameter Has Gone Away.

TIP

The compareTo method of the Comparable interface returns an integer. If the objects are not equal, it does not matter what negative or positive value you return. This flexibility can be useful when you are comparing integer fields. For example, suppose each employee has a unique integer id and you want to sort by employee ID number Then you can simply return id -.. other.id That value will be some negative value if the first ID number is less than the other, 0 if they are the same ID, . and some positive value otherwise However, there is one caveat: The range of the integers must be small enough that the subtraction does not overflow If you know that the IDs are not negative or that their absolute value is at most (Integer.MAX_VALUE. - 1) / 2 YOU ARE SAFE.OF Course, The Subtraction Trick Doesn't Work for floating-point number. The Difference Salry - Other.salary Can Round To 0 if The Salaries Are Close Together But Not Identical.

Now you saw what a class must do to avail itself of the sorting service-it must implement a compareTo method. That's eminently reasonable. There needs to be some way for the sort method to compare objects. But why can not the Employee class simply PROVIDE A COMPARETO METHOD WITHOUT IMPLEMENTING THE COMPARABLE INTERFACE?

The reason for interfaces is that the Java programming language is strongly typed. When making a method call, the compiler needs to be able to check that the method actually exists. (Java is mandatory type of language, when called as a method, the compiler Need to check all the actual presence.) Somewhere in The Sort Method Will Be Statements Like this:

IF (a [i] .compareto (a [j])> 0)

{

//RRANGE A [i] and a [j]

.

}

The compiler must know that a [i] actually has a compareTo method. If a is an array of Comparable objects, then the existence of the method is assured because every class that implements the Comparable interface must supply the method.NOTE

You would expect that the sort method in the Arrays class is defined to accept a Comparable [] array so that the compiler can complain if anyone ever calls sort with an array whose element type does not implement the Comparable interface. Sadly, that is not The Case. Instead, The Sort Method Accepts An Object [] Array and Uses a CLUMSY CAST:

// from the standard library - not recommented

IF ((Comparable) a [i]). Compareto (a [j])> 0)

{

//RRANGE A [i] and a [j]

.

}

IF a [i] does Not Belong to a class what imports the comparable interface, The Virtual Machine throws an exception.

Example 6-1 Presents The Full Code for Sorting An Employee Array.

EXAMPLE 6-1. Employeesorttest.java

Import java.util. *;

2.

3. Public Class Employeesorttest

4. {

5. Public static void main (String [] ARGS)

6. {

7. Employee [] Staff = new Employee [3];

8.

9. Staff [0] = New Employee ("Harry Hacker", 35000);

10. Staff [1] = New Employee ("Carl Cracker", 75000);

11. Staff [2] = New Employee ("Tony Tester", 38000);

12.

13. Arrays.Sort (STAFF);

14.

15. // Print Out Information about ALL Employee Objects

16. For (Employee E: STAFF)

17. System.out.println ("Name =" E.GETNAME () ", SALARY =" E.GETSALARY ());

18.}

19.}

20.

21. Class Employee Implements Comparable

twenty two. {

23. Public Employee (String n, double s)

twenty four. {

25. Name = n; 26. SALARY = S;

27.}

28.

29. Public string getName ()

30. {

31. Return Name;

32.}

33.

34. Public Double GetSalary ()

35. {

36. Return Saliff;

37.}

38.

39. Public Void RaisSalary (double bypercent)

40. {

41. Double Raise = Salary * bypercent / 100;

42. Salary = raise;

43.}

44.

45. / **

46. ​​Compares Employees by Salary

47. @Param Other Another Employee Object

48. @return a Negative Value IF this Employee Has a Lower

49. Salary Than OtherObject, 0 if The Salaries Are The Same,

50. a Positive Value OtherWise

51. * /

52. Public Int Compareto (Employee Other)

53. {

54. IF (Salary

55. IF (Salary> Other.salary) Return 1;

56. RETURN 0;

57.}

58.

59. PRIVATE STRING NAME

60. PRIVATE DOUBLE SALY;

61.}

API

Java.lang.comparable 1.0

"Int Compareto (Object OtherObject)

Compares this Object with OtherObject and returns a Negative INTEGER IF this Object is Less Than OtherObject, ZERO IF THEY Are Equal, and a posient integer Otherwise.

Java.lang.comParable 5.0

Int Compareto (T Other)

Compares this Object With Other and returns a negative INTEGER IF this Object is Less Than Other, ZERO IF THEY ARE Equal, And A Positive Integer Otherwise.

Java.util.arrays 1.2

"Static void sort (Object [] A)

sorts the elements in the array a, using a tuned mergesort algorithm (algorithm merge sort). All elements in the array must belong to classes that implement the Comparable interface, and they must all be comparable to each other.

Note

According to the language standard: "THE IMPARETO (Y)) = -sgn (Y.Compareto (x)) for all x and y. (This Implies That X.Compareto (Y) Must Throw AN Exception if Y.comPareto (x) throws an exception.) "Here," SGN "is the Sign of a Number: SGN (N) IS -1 IF N IS NEGATIVE, 0 IF N Equals 0, And 1 IF N IS POSTIVE ........................ ..

As with the equals method, problems can arise when.

Because Manager extends Employee, it implements Comparable and not Comparable If Manager chooses to override compareTo, it must be prepared to compare managers to employees It can not simply cast the employee to a manager..:

Class Manager EXTENDS EMPLOYEE

{

Public int compareto (EMPLOYEE OTHER)

{

Manager othermanager = (manager) other; // no

.

}

.

}

That Violates The "AntiSymmetry" rule ("Anti-Professional" principle). IF x is an Employee and y is a manager, THE CALL X.Compareto (Y) Doesn't throw an exception-it simply Compares x and y as Employees. But The Reverse, Y.comPareto (x), Throws a classcastexception.

...................... ...

If SUBCLASS HAVE DIFFERENT NOTITIONS OF Comparison, THEN You Should Outlaw Comparison Of Objects That Belong To Different Classes. Each Compareto Method Should Start Out with the Test

IF (getClass ()! = other.getClass ()) throw new classcastexception ();

If there is a common algorithm for comparing subclass objects, simply provide a single compareTo method in the superclass and declare it as final.For example, suppose that you want managers to be better than regular employees, regardless of the salary. What about other subclasses such as Executive and Secretary? If you need to establish a pecking order, supply a method such as rank in the Employee class. Have each subclass override rank, and implement a single compareTo method that takes the rank values ​​into account.

Properties of Interfaces, PROPERTIES OF INTERFCES

Interfaces Are Not Classes. In Particular, You Can Never Use The New Operator To Instantiate An Interface (You cannot use new interface to initialize an interface):

X = new comparable (...); // error

However, Even Though You can't Construct Interface Objects, You CAN Still Declare Interface Variables (although interface objects can be declared).

Comparable x; // ok

An Interface Variable Must Refer to an Object of a Class That Implements The interface must point to an object to implement the class that implements the interface):

x = new employee (..); // ok provided Employee Implements Compailable

Next, Just As You Use InstanceOf to Check WHETHER AN Object IS OF A Specific Class, You CAN Use InstanceOf To Check WHETHER An Object Implements An Interface (You can use the InstanceOf operator to check if an interface is implemented):

IF (anObject instanceof comparable) {..

Just as you can build hierarchies of classes, you can extend interfaces (interfaces can be inherited). This allows for multiple chains of interfaces that go from a greater degree of generality to a greater degree of specialization. For example, suppose you had an interface called Moveable.

Public Interface Moveable

{

Void Move (double x, double y);

}

THEN, You Could IMAGINE AN ​​Interface Called Powered That Extends It: Public Interface Powered Extens Moveable

{

Double Milespergallon ();

}

Although you cannot put instance field, you can support, you can supply constants in the (although there is no instance or static method in the interface, it can provide constants). For example:

Public Interface Powered Extends Moveable

{

Double Milespergallon ();

Double Speed_Limit = 95; // a public static final constant

}

Just As Methods In an Interface Are Automatically Public, Fields Are ALWAYS PUBLIC STATIC FINAL is always public static final for Public Static Final.

Note

IT is Legal To Tag Interface Methods As Public, And Fields As Public Static Final. Some Programmers Do That, Either Out of Habit Or for Greater Clarity.

However, The Java Language Specification Recommends That The Redundant Keywords Not Beu Supplied

(Java language specification recommended not to use these excess keywords)

,

And We Follow That Recommendation.

Some interfaces define just constants and no methods (some interface defines constants and no methods). For example, the standard library contains an interface SwingConstants that defines constants NORTH, SOUTH, HORIZONTAL, and so on. Any class that chooses to implement the SwingConstants interface automatically inherits these constants. Its methods can simply refer to this method NORTH rather than the more cumbersome SwingConstants.NORTH. However, this use of interfaces seems rather degenerate, and we do not recommend it (the interface with the interface seems Essentially is off, we do not recommend it).

While Each Class Can Have Only One Superclass, Classes CAN Implement Multiple Interfaces. This Gives You The Maximum Amount of Flexibility In Defining a class's behavior (each class can only have a super class, but you can implement multiple interfaces. This makes there are class acts defined maximum flexibility). For example, the Java programming language has an important interface built into it, called Cloneable. (We discuss this interface in detail in the next section.) If your class implements Cloneable, the clone method in the Object class will make an exact copy of your class's objects. Suppose, therefore, you want cloneability and comparability. Then you simply implement both interfaces.class Employee implements Cloneable, Comparable

Use Commas to Separate The Interfaces That Describe The Characteristics That You Want To Supply.

Interfaces and Abstract Classes

If you read the section about abstract classes in Chapter 5, you may wonder why the designers of the Java programming language bothered with introducing the concept of interfaces Why can not Comparable simply be an abstract class.:

Abstract Class Comparable // Why Not?

{

Public Abstract Int Compato (Object Other);

}

THE EMPLOYEE CLASS WOULD THEEN SIMPLY EXTEND THIS Abstract Class and Supply The Compareto Method:

Class Employee EXTENDS Comparable // Why NOT?

{

Public int compareto (Object Other) {..

}

There is, unfortunately, a major problem with using an abstract base class to express a generic property. A class can only extend a single class. Suppose that the Employee class already extends a different class, say, Person. Then it can not extend A Second Class.

Class Employee Extends Person, Comparable // Error

But Each Class CAN Implement As Many Interfaces As IT Likes:

class Employee extends Person implements Comparable // OKOther programming languages, in particular C , allow a class to have more than one superclass. This feature is called multiple inheritance (multiple inheritance). The designers of Java chose not to support multiple inheritance, because it Makes The Language Either Very Complex (AS IN C ) Or Less Efficient (AS in Eiffel).

INSTEAD, Interfaces Afford Most of The Benefctions of Multiple Inheritance While Avoiding The ComplexIns and INEfficiencies.

C Note

C has multiple inheritance and all the complications that come with it, such as virtual base classes, dominance rules, and transverse pointer casts. Few C programmers use multiple inheritance, and some say it should never be used. Other programmers recommend using multiple inheritance only for "mix in" style inheritance. in the mix-in style, a primary base class describes the parent object, and additional base classes (the so-called mix-ins) may supply auxiliary characteristics. That style is similar to a Java class WITH A SINGLE BASE CLASS AND Additional Interfaces. However, In C , Mix-ins can the Mix - INS CAN ADD Default Behavior, Whereas Java Interfaces Cannot.

转载请注明原文地址:https://www.9cbs.com/read-131280.html

New Post(0)