Thinking logic of computer programs (19), thinking Logic
Restrictions on Data Types
Previously, we have been saying that programs mainly involve data and data operations. To facilitate data operations, the advanced language introduces the concept of data types. Java defines eight basic data types, A class is equivalent to a custom data type. It can represent and operate various things or objects through the combination and Inheritance of classes.
However, this only treats an object as a data type and operates on it. In some cases, it does not reflect the object and the nature of object operations.
Why? Most of the time, what we actually care about is not the object type, but the object capability. As long as this capability is provided, the type is not important. Let's look at some examples of life.
Many times, you only need to take a photo that meets your needs. It doesn't matter if you use a mobile phone, Pad, or SLR camera, the concern is whether the object has the ability to take photos, rather than the type of the object. Mobile phones, tablets, or SLR cameras can all be used.
To calculate a set of numbers, you only need to calculate the correct results. As a result, it is not important to use abacus, calculator, and computer software, the concern is whether the object has the computing capability, rather than whether it is an abacus or a calculator.
To heat the cold water, as long as you can get hot water, so it is not important to use an Induction Cooker to heat, use a gas stove to heat, or use an electric hot water bottle. What is important is whether the object has the ability to add hot water, it does not care about the object type.
In these cases, the type is not important, but the capability is important. How can we express our capabilities?
Interface Concept
Java uses the interface to express its capabilities.
The concept of interface is no stranger in life. A common interface in the electronic world is the USB interface. Computers often have multiple USB interfaces that can be inserted into a variety of USB devices, such as the keyboard, mouse, USB flash drive, camera, and mobile phone.
An interface declares a set of capabilities, but it does not implement this capability by itself. It is just a convention that involves two-party interaction objects. One party needs to implement this interface, and the other party uses this interface, however, objects on both sides are not directly dependent on each other. They only interact indirectly through interfaces. The figure is as follows:
Taking the above USB interface as an example, the USB Protocol specifies the capabilities required by the USB device. Each USB device must implement these capabilities. The computer uses the USB protocol to interact with the USB device, computers and USB devices do not depend on each other, but they can interact with each other through the USB interface.
Let's take a look at the interfaces in Java.
Interface Definition
An example is provided to illustrate the concept of interfaces in Java.
This example is "comparison". Many objects can be compared. For programs that evaluate the maximum value, minimum value, and sorting, they do not actually care about the object type, only objects can be compared, or they are concerned about whether objects can be compared. Java API provides the Comparable interface to indicate Comparable capabilities, but it uses generics, and we have not introduced generics. Therefore, in this section, we define a Comparable interface called MyComparable.
Now, first, Let's define this interface. The Code is as follows:
public interface MyComparable { int compareTo(Object other);}
Explanations:
- Java uses the interface keyword to declare the interface. The modifiers are generally public.
- The interface is followed by the interface name MyComparable.
- In the interface definition, a method compareTo is declared, but no method body is defined, and no method is implemented for the interface. You do not need to add modifiers to or from interface methods. They cannot be other modifiers.
Let's explain the compareTo method:
- The method parameter is an Object-type variable other, indicating another Object involved in the comparison.
- The first object involved in the comparison is yourself.
- The returned result is of the int type.-1 indicates that the value is smaller than the parameter object, 0 indicates that the value is the same, and 1 indicates that the value is greater than the parameter object.
Interfaces and classes are different. Their methods do not implement code. Defining an interface itself is not doing anything, and it is not very useful. It requires at least two participants, one implementing the interface and the other using the interface. Let's first implement the interface.
Implementation Interface
Class can implement the interface, indicating that the class object has the ability expressed by the interface. Let's take a look at an example. The Point class we have previously introduced shows that Point can be compared. How can we compare points? Let's assume that the distance from the origin is compared. The following is the Point class 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+")"; }}
Let's explain:
- Java uses the implements keyword to indicate the implementation interface. The class name is first followed by the interface name.
- To implement an interface, you must implement the methods declared in the interface. Point implements the compareTo method.
Let's explain the compareTo Implementation of Point:
- Point cannot be compared with other types of objects. It first checks whether the object to be compared is of the Point type. If not, throw is used to throw an exception. The exception is not mentioned yet, this can be ignored.
- If it is of the Point type, use forced type conversion to convert the Object type parameter other to the Point type parameter otherPoint.
- This explicit type check and forced conversion can be avoided using the generic mechanism. We will introduce the generic type later.
A class can implement multiple interfaces, indicating that the class objects have multiple capabilities. interfaces are separated by commas. The syntax is as follows:
public class Test implements Interface1, Interface2 {....}
The interface is defined and implemented. Next, let's look at how to use the interface.
Interface
Unlike a class, an interface cannot be new, and an interface object cannot be created directly. An object can only be created through a class. However, you can declare variables of the interface type and reference the class objects that implement the interface. For example, you can:
MyComparable p1 = new Point(2,3);MyComparable p2 = new Point(1,2);System.out.println(p1.compareTo(p2));
P1 and p2 are variables of the MyComparable type, but reference objects of the Point type. The reason why Point can be assigned a value is that Point implements the MyComparable interface. If a type implements multiple interfaces, this type of object can be assigned to any interface type variable.
P1 and p2 can call the methods of the MyComparable interface, and can only call the methods of the MyComparable interface. during actual execution, the code of the specific implementation class is executed.
Why does an object of the Point type have to be assigned a value to a variable of the MyComparable type? In the above Code, it is really unnecessary. However, in some programs, the Code does not know the specific type. This is the power of the interface. Let's look at the example of using the MyComparable interface below.
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++){ 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; } } } }}
The CompUtil class provides two methods. max obtains the maximum value in the input array, and sort sorts the array in ascending order. The parameters are all arrays of the MyComparable type. Max's code is easy to understand and will not be explained. sort uses Bubble sorting. The details of this code will be explained in subsequent articles.
It can be seen that this class is designed for the MyComparable interface. It does not know what the specific type is or care about it, but can operate on any type that implements the MyComparable interface. Let's take a look at the operation on the Point type. The Code is as follows:
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));
Create an array points of the Point type, use the max method of CompUtil to obtain the maximum value, use sort to sort and output the result. The output is as follows:
max: (3,4)sort: [(1,2), (2,3), (3,4)]
The operation on the Point array is demonstrated here. In fact, the operation can be performed on any type array that implements the MyComparable interface.
This is the power of interfaces. It can be said that programming for interfaces rather than specific types is an important way of thinking for computer programs. For interfaces, objects and operations on objects are often reflected. It has many advantages. The first is code reuse. The same set of code can process multiple different types of objects, as long as these objects have the same capabilities, such as CompUtil.
More importantly, it reduces coupling and increases flexibility. The code that uses the interface depends on the Interface itself, rather than the specific type of the interface. The program can replace the interface implementation as needed, the interface user is not affected. The key to solving complex problems is to divide and conquer the problem. However, there is no possible relationship between small problems. The core of decomposition is to reduce coupling and improve flexibility. The interface should be properly decomposed, provides powerful tools.
Interface Details
The basic content of the interface is described above. The interface also has some details, including:
- Variables in the interface
- Interface inheritance
- Class inheritance and interfaces
- Instanceof
Let's introduce them one by one.
Variables in the interface
You can define variables in the interface. The syntax is as follows:
public interface Interface1 { public static final int a = 0;}
A variable int a is defined here. The modifier is public static final, but this modifier is optional. Even if it is not written, it is also public static final. This variable can be used in the form of "interface name. variable name", such as Interface1.a.
Interface inheritance
An interface can also be inherited. An interface can inherit other interfaces. The basic concept of inheritance is the same as that of a class. But unlike a class, an interface can have multiple parent interfaces. The Code is as follows:
public interface IBase1 { void method1();}public interface IBase2 { void method2();}public interface IChild extends IBase1, IBase2 {}
The extends keyword is also used for interface inheritance. Multiple parent interfaces are separated by commas.
Class inheritance and interfaces
Class inheritance and interfaces can coexist. In other words, a class can implement one or more interfaces while inheriting the base class. The syntax is as follows:
public class Child extends Base implements IChild { //...}
Extends must be placed before implements.
Instanceof
Like a class, an interface can also use the instanceof keyword to determine whether an object has implemented an interface. For example:
Point p = new Point(2,3);if(p instanceof MyComparable){ System.out.println("comparable");}
Use interfaces to replace inheritance
As mentioned above, you can use interfaces to replace inheritance. How can this problem be replaced?
We can say that inheritance has at least two advantages: reusing code, and using polymorphism and dynamic binding to uniformly process objects of different sub-classes.
Use combination to replace inheritance. Code can be reused but cannot be processed in a unified manner. You can use interfaces to program interfaces to process different types of objects in a unified manner, but the interfaces do not have code implementation and cannot reuse code. Combining grouping and interfaces enables both unified processing and code reuse. We will illustrate the above examples.
We first add an interface IAdd with the following code:
public interface IAdd { void add(int number); void addAll(int[] numbers);}
Modify the Base code to implement the IAdd interface. The Code remains unchanged:
public class Base implements IAdd {//...}
Modifying the Child Code is also the IAdd interface, and the code remains unchanged:
public class Child implements IAdd { //...}
In this way, the code can be reused or processed in a unified manner without worrying about cracking the encapsulation.
Summary
In this section, we talk about the limitations of data-type thinking. We mentioned that we often care about capabilities rather than types, So we introduced interfaces and introduced the concepts and details of interfaces in Java, interface Programming is an important way of thinking. This method can not only reuse code, but also reduce coupling and improve flexibility. It is an important tool for decomposing complex problems.
The interface does not have any implementation code, and the previously introduced classes have complete implementation and can all create objects. in Java, there is also a concept between interfaces and classes, abstract classes, what is its use?
----------------
For more information, see the latest article. Please pay attention to the Public Account "lauma says programming" (scan the QR code below), from entry to advanced, ma and you explore the essence of Java programming and computer technology. Write with your heart, original articles, and retain all copyrights.