Java programming logic (19) - the nature of the interface

Data types of limitations

We have been saying before, the main program is the data and operations on the data, while the data for easy operation, high-level language to introduce the concept of data types, Java defines eight basic data types, and classes are equivalent to custom data types, by the combination of class and inheritance can represent and manipulate a variety of things or objects.

However, this is only seen as an object belonging to a data type, according to the type of operation, in some cases, and does not reflect the nature of the objects and object manipulation.

Why do you say? In many cases, the type is not an object we actually care about, but the ability to object, as long as the ability to provide this type is not important. Let's look at some examples of life.

To take a photo, many times, as long as meet the needs of the photo shoot on the line, as is using a mobile phone, or use Pad shot, or shoot with SLR cameras, it does not matter, care about is whether the object has a photo shoot capacity, and does not care what type of objects in the end, cell phone, Pad or SLR cameras can.

To calculate a set of numbers, as long as it can calculate the correct result, as is, by the people count abacus mental arithmetic, use the calculator, computer software operator, it does not matter, care about is whether the object has the ability to calculate, and objects in the end is not concerned with the abacus or calculator.

To heat the cold water, hot water can be obtained as long as you can, as is heating appliance, heating with gas stoves, or electric kettle, is not important, important is whether the object has the ability to heat water, and do not care about the object in the end What types.

In these cases, the type is not important, important is the ability. How it means the ability to do?

Interface concept

Java uses the concept interface representation capability.

Interface This concept is not new in life, electronic world a common interface is USB interface. PCs often have more than one USB port, you can plug a variety of USB devices can be a keyboard, mouse, U disk, camera, mobile phone and so on.

Interface declares a set of capabilities, but he did not realize this ability, it's just a convention, it involves two parties interacting objects, a party needs to implement this interface, the other using this interface, but both objects are not directly dependent on each other, they only indirectly through the interactive interface. Illustrated as follows:


Take it above the USB interface, USB agreement requires the ability to achieve USB devices, USB devices are required to implement each of these capabilities, the computer using the USB protocol to interact with USB devices, computers and USB devices are not mutually dependent, but can be via USB interface to interact with each other.

Here we look at the Java interface.

Defined interfaces

We illustrate the concept of Java interfaces through an example.

This example is the "more", many objects can be compared to procedures for seeking the maximum, minimum, sort of, in fact, they do not care about the type of what the object is, as long as the object can compare it, or, they care about is the ability to target not comparable. Java provides the API Comparable interface, the ability to represent comparable, but it uses a generic, but we have not introduced generics, so this section, we own define a Comparable interface, called MyComparable.

Now, first of all, let's define this interface, as follows:

public interface MyComparable {
    int compareTo(Object other);
}

explain:

  • Java interface to use this keyword to declare an interface modifiers are generally public.
  • Behind the interface is the name of the interface MyComparable.
  • Inside the interface definition, a single method compareTo, but does not define method body, not the interface implementation. Interface method does not require additional modifiers, with and without are public, it can not be other modifiers.

Explain again compareTo method:

  • Method parameter is a variable of type Object other, represents another object participating comparison.
  • The first object to compare their own participation
  • The result is an int, the object parameter is less than -1 for own, 0 for the same, that is greater than a parameter object

Interface classes, it does not implement the method code. A definition of the interface itself did not do anything, there is not much use, it requires at least two participants, a need to implement the interface and the other using the interface, let's implement the interface.

Implement an interface

Class can implement the interface, the object class indicates the ability to interface representation. We look at an example to the previously explained Point class to show that we have the ability to make Point comparable, how the comparison between Point it? We assume that according to the distance from the origin are compared, the following is the Point class code:

Copy the code
public class Point implements MyComparable {
    private int x;
    private int y;
    
    public Point(int x, int y) {
        this.x = x;
        this.y = y;
    }
    
    public double distance(){
        return Math.sqrt(x*x+y*y);
    }

    @Override
    public int compareTo(Object other) {
        if(!(other instanceof Point)){
            throw new IllegalArgumentException();
        }
        Point otherPoint = (Point)other;
        double delta = distance() - otherPoint.distance();
        if(delta<0){
            return -1;
        }else if(delta>0){
            return 1;
        }else{
            return 0;
        }
    }

    @Override
    public String toString() {
        return "("+x+","+y+")";
    }
}
Copy the code


We explain:

  • Java uses the keyword indicates that implements the interface to achieve, in front of the class name, followed by the interface name.
  • Must implement the interface methods declared in the interface to be achieved, Point implement a compareTo method.

Let us explain compareTo Point of implementation:

  • Point can not compare with other types of objects, it first checks whether the object is to compare the Point type, if not, use the throw throws an exception, we have not mentioned abnormal, follow-up article to explain, here is negligible.
  • If the Point type, Object type cast using other parameters are converted to parameters of type Point otherPoint.
  • This explicit type checking and coercion can use the generic mechanism to avoid the follow-up article we will introduce generics.

 A class can implement multiple interfaces, indicates that the object class is provided with multiple capabilities, the interface between the respective separated by commas, syntax is as follows:

public class Test implements Interface1, Interface2 {

....

}

Define and implement an interface, then we look at how to use the interface.

Use Interface

Unlike classes, interfaces can not be new, can not create a direct interface object, the object can only be created by the class. However, the interface can declare a variable of type class object reference implementation of the interface. For example, it can be:

MyComparable p1 = new Point(2,3);
MyComparable p2 = new Point(1,2);
System.out.println(p1.compareTo(p2));

p1 and p2 are MyComparable type of variable, but refers to an object of type Point, has been able to assign because Point implements MyComparable interface. If a plurality of types of implements interfaces that the object of this type can be assigned to any one of the interface type of the variable.

p1 and p2 can call MyComparable interface method, the method can only be called MyComparable interface, the actual implementation, the execution code implementation class.

Why is the object of type Point MyComparable have to be assigned to a variable of type it? In the above code, really is not necessary. However, in some programs, the code does not know the specific type, this is where the interface power play, look at the following example we use MyComparable interface.

Copy the code
public class CompUtil {
    public static Object max(MyComparable[] objs){
        if(objs==null||objs.length==0){
            return null;
        }
        MyComparable max = objs[0];
        for(int i=1;i<objs.length;i++){
            if(max.compareTo(objs[i])<0){
                max = objs[i];
            }
        }
        return max;
    }
    
    public static void sort(MyComparable[] objs){
        for(int i=0;i<objs.length;i++){
            int min = i;
            for(int j=i+1;j<objs.length;j++){
                if(objs[j].compareTo(objs[min])<0){
                    min = j;
                }
            }
            if(min!=i){
                 MyComparable temp = objs[i];
                 objs[i] = objs[min];
                 objs[min] = temp;
            }
        }
    }
}
Copy the code

 

CompUtil class provides two methods, max maximum value acquiring incoming array, sort in ascending order sorted array, the array type parameters are MyComparable. max code is easier to understand, not explained, sort sorted using a simple choice.

As can be seen, this class is for MyComparable programming interface, it does not know what specific type that does not care, but it can be realized for any type MyComparable interface to operate. Point we look at the type of operation, as follows:

Copy the code
Point[] points = new Point[]{
        new Point(2,3),
        new Point(3,4),
        new Point(1,2)
};
System.out.println("max: " + CompUtil.max(points));
CompUtil.sort(points);
System.out.println("sort: "+ Arrays.toString(points));
Copy the code

Creating a Point array of Points types, then obtaining the maximum value max CompUtil method, with the sort order, and outputs the result, output:

max: (3,4)
sort: [(1,2), (2,3), (3,4)]

Point here is to demonstrate an array of operations, in fact, can operate on any type of array to achieve a MyComparable interface.

This is the power of the interface, it can be said, for the programming interfaces rather than specific types, is an important way of thinking computer program. For the interface, often reflecting the nature of the subject and object manipulation. It has many advantages, first of code reuse, the same set of code that can handle many different types of objects, as long as these objects have the same capability, as CompUtil.

More important to reduce coupling, increase the flexibility, the use of the interface is dependent on the interface code itself, rather than to achieve particular type of interface, the interface program may be implemented in some cases replace, without affecting the user interfaces. The key to solving complex problems is to divide and rule, broken down into small problems, but it is impossible between a small problem had nothing, core decomposition is to reduce coupling, increase flexibility, the interface is appropriate decomposition, provides a powerful tool.

Interface details

Above us the basic elements of the interface, there are some details of the interface, including:

  • Interface variables
  • Inherited interface
  • Inheritance and interface class
  • instanceof

We introduced one by one to the next.

Interface variables

Interface can define a variable, syntax is as follows:

public interface Interface1 {
    public static final int a = 0;
}

Here the definition of a variable int a, modifier is public static final, but this modifier is optional, if not write, but also public static final. This variable can be used by "interface name variable name" approach, such as Interface1.a.

Inherited interface

An interface can inherit an interface to other interfaces can be inherited, inherited as the basic concept of the class, but the class, the interface can have more than one parent interface code as follows:

Copy the code
public interface IBase1 {
    void method1();
}

public interface IBase2 {
    void method2();
}

public interface IChild extends IBase1, IBase2 {
}
Copy the code

Inherit the same interface extends keyword, separated by commas between multiple parent interfaces.

Inheritance and interface class

Class inheritance and interfaces can coexist, in other words, a class can inherit in the case of the base class, while achieving one or more interfaces, syntax is as follows:

public class Child extends Base implements IChild {

 //...

}

extends to be placed before the implements.

instanceof

And classes, interfaces may be used instanceof keyword, to determine whether an object implements an interface, for example:

Point p = new Point(2,3);
if(p instanceof MyComparable){
    System.out.println("comparable");
}

Use an alternative interface to inherit

We mentioned in the previous section, you can use the interface to replace inheritance. How replace it?

We say to inherit at least two advantages, one is code reuse, and the other is the use of polymorphism and dynamic binding unity handle a variety of objects of different subclasses.

Use a combination of alternative inheritance, the code can be reused, but not unified treatment. Use interface for programming interfaces Objects can be unified treatment of different types, but the interface does not implement the code, not code reuse. Combine portfolios and interfaces, it may be unitary, or may be code multiplexed. We still examples to illustrate the above section.

Let's increase an interface IAdd, code is as follows:

public interface IAdd {
    void add(int number);
    void addAll(int[] numbers);
}

Base modify the code, let him achieve IAdd interface code is essentially the same:

public class Base implements IAdd {

//...

}

Modify Child codes, but also to achieve IAdd interface code is essentially the same:

public class Child implements IAdd {

 //...

}

Thus, not only you can reuse the code, you can centrally, but do not worry about damage to the package.

summary

In this section we discuss the limitations of the data type of thinking, often mentioned concern is the ability, rather than type, so the introduction of the interface, introduces the concept and details of Java interfaces, and programming interfaces for the program is an important way of thinking this way not only can reuse code, you can also reduce coupling, increase flexibility, it is an important tool to break down complex problems.

Interface has no implementation code, and has a complete implementation class before the introduction, you can create objects, Java also has a concept between the range of interfaces and classes, abstract classes, what does it do with it?

Guess you like

Origin www.cnblogs.com/ivy-xu/p/12387374.html