From http://www.cnblogs.com/ggjucheng/archive/2012/12/04/2802265.html
English from http://docs.oracle.com/javase/tutorial/java/IandI/usinginterface.html
Declare a class implementation interface and include an implements statement in the class declaration. Class can implement multiple interfaces, so the implements keyword is followed by a comma to separate the interfaces implemented by this class. By convention, if a parent class inherits, the implements statement follows the extend statement.
A simple interface, relatable
Consider the following interface definition to compare the object size
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 compare the sizes of two similar objects without worrying about what they are, the instantiated class should implement the relatable interface.
Any class can be implemented only when it has a method to compare the size of the instantiated object.Relatable. For strings, it can compare the number of characters, for books, you can compare the number of pages, for students, you can compare the weight and so on. For geometric objects in a plane, area is a good choice (see the rectangleplus class below). For Three-dimensional Geometric objects, you can use volume comparison. All these classes can implement the islargerthan () method.
Implement the relatable Interface
Here isImplementation of the rectangle interface:
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 ;}}
BecauseRectangleplus implementedRelatable
, So any twoRectangleplus objects can all be compared
Note:Relatable interface definition methodIslargerthan, only acceptRelatable
Type object. Convert otherThe row of the rectangleplus instanceCode. Type conversion tells the compiler what type the object is. Direct callOther instanceThe other. getarea () method will fail because the compiler does not know that the other is actuallyRectangleplus
Instance.