Java official note 7 interface

interface

Interfaces can only contain: constants, method signatures(abstract), default methods, static methods, and nested types

The method body only exists in: default methods and static methods

Interfaces cannot be instantiated, they can only be implemented by classes, or inherited by other interfaces (interfaces can be multi-inherited).

Define the interface:

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
}

The class implements the interface:

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
}

If the interface is not public, it can only be implemented by classes in the same package.

implement the interface

interface:

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);
}

accomplish:

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;               
    }
}

For interfaces:

public interface DoIt {
   void doSomething(int i, double x);
   int doSomethingElse(String s);
}

If you want to add a new method, in order to avoid affecting all classes that have implemented the interface, there are several ways:

① Inheritance

public interface DoItPlus extends DoIt {

   boolean didItWork(int i, double x, String s);
   
}

②default method

public interface DoIt {

   void doSomething(int i, double x);
   int doSomethingElse(String s);
   default boolean didItWork(int i, double x, String s) {
       // Method body 
   }
}

If the interface is inherited, then the default method of the subinterface may appear:

  1. No declaration, inherit the default method of the parent interface
  2. The statement becomes an abstract method, and the implementation class must implement this method (that is, the parent class defaults, but the subclass does not default)
  3. Declare and override, the default method of the subclass shall prevail

③static method

public interface TimeClient {
    // ...
    static public ZoneId getZoneId (String zoneString) {
        try {
            return ZoneId.of(zoneString);
        } catch (DateTimeException e) {
            System.err.println("Invalid time zone: " + zoneString +
                "; using default time zone instead.");
            return ZoneId.systemDefault();
        }
    }

    default public ZonedDateTime getZonedDateTime(String zoneString) {
        return ZonedDateTime.of(getLocalDateTime(), getZoneId(zoneString));
    }    
}

The static method of the interface is equivalent to extracting the static methods of multiple classes to a common place, and the classes that implement the interface all have static methods.

Interface Type

Interfaces can also be used as types:

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;
}

The assignment object of an interface type must be an instance of a class that implements the interface.

References:

https://dev.java/learn/interfaces/

Guess you like

Origin blog.csdn.net/weixin_45741835/article/details/131059508
Recommended