Expand the class (one:: Interface essence) (2-5-1) Object-Oriented

Disclaimer: This article is a blogger original article, shall not be reproduced without the bloggers allowed. https://blog.csdn.net/gaolh89/article/details/80629915

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, while class equivalent custom data types, and by a combination of derived classes can represent and manipulate a variety of things or objects.

In addition to basic data types and generic concept, and some extended concept, including interfaces, abstract classes, and internal class enumeration. The last chapter we mentioned, there are two sides to inherit, inheritance is a way to replace the use of the interface, the interface in the end what is it Moreover, between interfaces and classes, as well as a concept:? Abstract class what it is You? a class can be defined inside another class, called inner classes, why have inner class, which in the end what is it? enumeration is a special type of data, what use is it?

In order to clarify the problems described above, it will be divided into two sections to learn, as used herein a first section, the second section is "object oriented: Development class (II: abstract class, inner classes, essentially enumeration)"


In the previous chapters, we have been emphasizing the concept of data types, but only the object as belonging to a certain type of data, according to the type of operation, in some cases, does not reflect the nature of objects and their operations.

Why do you say that? Many times, we really care about is not the type of object, but the ability to object, as long as the ability to provide this type is not important. Let's look at an example of life.

For example, to take pictures, many times, as long as meet the needs of the photo shoot on the line, as is using a mobile phone, or use Pad shoot, shoot or SLR, it does not matter that concerned about is: whether the object has the ability to shoot photos , but does not care what type of objects in the end , phone, Pad or SLR cameras can.

Switch to the program's logical thinking: type is not important, important is the ability of how it means the ability to interface to it.?.

Here, the interface will be described in detail, including its concept, usage, some of the details, and how to use the interface to inherit instead.

Concepts Interface

Interface This concept is not new in life, electronic world is a common interface to the USB interface. The computer often have a lot of USB interface, you can plug a variety of USB devices such as keyboard, mouse, U disk.

Interface declares a set of capabilities, but he did not realize this ability, it's just a convention interface interactions involving both objects, a party needs to implement this interface, the other using this interface , but both objects are not directly dependent on each other, they indirect interaction only through the interface, as shown below:

Write pictures described here

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. that, Java Interface and how is it?

2. Define Interface

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 object is what, as long as the objects may be compared to it, or that they are concerned about is the ability to target not comparable .Java API provides comparable interface, the ability to represent comparable, but this chapter is to explain the main interface, we first their definition of a Comparable interface, called MyComparable.

First, the interfaces are defined, as follows:

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

Code defines the interface is explained as follows:
1) the Java interface to use this keyword to declare an interface modifiers are generally public.
2) interface is the name behind the interface MyComparable.
3) inside the interface definition, a single method compareTo, but no the method defined body before Java 8, the interface can not implement the method. the method does not require adding an interface modifier, with and without corresponding to all public abstract.

Again explain compareTo method:
Parameter 1) the method is a variable of type Object other, represents a comparison of the object involved in the other.
2) will be compared with the object of their own.
3) returns a result of type int and -1 objects less than their parameters, refer to the same 0, 1 that is greater than the parameter object.

Interfaces and classes, it does not implement the method code defines an interface itself is nothing to do, there is not much use, it requires at least two. Participants : a need to implement the interface and the other using the interface.

3. Use Interface

Class can implement interfaces, object represents a class has the ability to interface represented. Our Point class to show we have the ability to make Point can be compared, the comparison between Point how? We assume that compares according to the distance from the origin, Point class code as follows:

public class Point implements MyComparable {

    private int x;
    private int y;

    public Point(int x, int y) {
        this.x = x;
        this.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 0;
        } else {
            return -1;
        }
    }

    @Override
    public String toString() {
        return "Point{" +
                "x=" + x +
                ", y=" + y +
                '}';
    }

    public double distance() {
        return Math.sqrt(x * x + y * y);
    }
}

Code is interpreted as follows:
1) the use of the Java implements this keyword indicates that implement the interface, in front of the class name, followed by the interface name.
2) must implement the interface methods declared in the interface to achieve, Point implement a compareTo method.

Point of compareTo explain again achieved.
1) Point can not be compared with other types of objects, it first checks whether the object is to compare the Point type, if not, throw an exception using the throw.
2) If Point type, use casts converted to other parameters of type Object Point type parameter otherPoint.
. 3) of this type checking and explicit force transducer is mounted by a generic mechanism can be avoided. generics on the use, will specifically later chapters introduction.

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 Text implements Interface1,Interface2{
    //主体代码
}

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

4. Interface

Unlike classes, interfaces can not be new, not directly founder of an interface object, the object can only be created by the class but. Declare a variable of type interfaces, reference implementation of the interface class object , for example, it may be this:

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

p1 and p2 are MyCompareable type of variable, but refers to an object of type Point, has been able to assign because Point implements MyCompareable interface if a type implements multiple interfaces, the object of this type can be assigned to either .p1 variable interface and an interface MyCompareable p2 can call a method, the method can only be called MyCompareable interface, the actual implementation, the execution code implementation class.

Why is the object of type Point MyCompareable 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 . We look Consider the following example using MyCompareable interface code is as follows:

public class CompUtil {

    public static Object max(MyComparable[] objs) {
        if (objs == null || objs.length == 0) {
            return null;
        }

        MyComparable max = objs[0];
        for (int i = 0; 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++) {
            for (int j = i + 1; j < objs.length; j++) {
                if (objs[i].compareTo(objs[j]) < 0) {
                    MyComparable temp = objs[i];
                    objs[i] = objs[j];
                    objs[j] = temp;
                }
            }
        }
    }   
}

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 using simple selection sort, we left the details of the follow-up article explains.

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. We see how the type of Point operation, code (class InterfaceActivity) as follows:

Point[] points = new Point[]{
                new Point(2, 3),
                new Point(3, 4),
                new Point(1, 2)
};

Log.e("最大值", "init: " + CompUtil.max(points));

CompUtil.sort(points);
Log.e("排序", "init: " + Arrays.toString(points));

Point code creates a type of an array, then obtaining the maximum value max CompUtil method, sorted with the sort printing results were as follows:

Write pictures described here

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, is programmed for the interface rather than a specific type, it is an important way of thinking computer program. Many times the interface reflects the nature of the objects 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 the interface coupling, increase the flexibility of code uses the interface is dependent on the interface itself, rather than to achieve the specific type of interface, the interface program may be implemented in some cases replace, without affecting the user interface to solve complex the key is to divide and conquer, 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.

The details of the interface
described previously the basic content of the interface, there are some details of the interface, comprising:

  • Interface variables
  • Inherited interface
  • Integration with interface class
  • instanceof

    The following specific description one by one.
    (1) interface a variable
    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

(2) interface inherit
an interface can inherit an interface to other interfaces can inherit the basic concept, and inherited class, but the class is different, the interface may have more than one parent interface (ie: multiple inheritance), the code is as follows It shows:

public interface IBase1 {
    void method1();
}

public interface IBase2 {
    void method2();
}

public interface IChild extends IBase1, IBase2 {
}

There are two IChild IBase1 and IBase2 parent interface, using the same interface inheritance extends keyword, separated by commas parent plurality of interfaces.

Interface inheritance and (3) the class
inherits the interface class 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 {
 //主体代码
}

Keywords extends to be placed before the implements.

(. 4) instanceof
with 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){
   Log.e("instanceof使用", "init: " + "comparable");
}

6. Use Interface alternative inheritance
before we mentioned, you can use a combination of inheritance and how alternative interface to replace it.?
Inherit at least two advantages , one is code reuse; the other is the use of polymorphism and dynamic binding and more unified treatment Object seeds of using a combination of alternative inheritance, you can reuse the code, but not centrally. using interface alternative inheritance, for interface programming, can achieve the object unified treatment of different types, but the interface is not implemented in code can not reuse code. the and a combination of interfaces combine alternative inheritance, you either centrally, and can reuse code.

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 {

    private static final int   MAX_NUM = 1000;
    private              int[] arr     = new int[MAX_NUM];
    private int count;

    public void add(int number) {
        if (count < MAX_NUM) {
            arr[count++] = number;
        }
    }


    public void addAll(int[] numbers) {
        for (int num : numbers) {
            add(num);
        }
    }
}

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

public class Child implements IAdd{

    private Base mBase;

    private long sum;

    public Child() {
        mBase = new Base();
    }


    public void add(int number) {
        mBase.add(number);
        sum += number;
    }


    public void addAll(int[] numbers) {
        mBase.addAll(numbers);
        for (int i = 0; i < numbers.length; i++) {
            sum += numbers[i];
        }
    }

    public long getSum() {
        return sum;
    }
}

Child Base reuse the code, they have achieved IAdd interfaces. In this way, code reuse, but also centrally, not fear of damaging the package.

7. Summary
In this paper 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 interfaces in Java, is an important program for the programming interface way of thinking, not only in this way can reuse code, you can also reduce coupling, increase flexibility, it is an important tool to break down complex problems.

Guess you like

Origin blog.csdn.net/gaolh89/article/details/80629915