[JAVA & amp; #183; elementary]: 13. Interface

Source: Internet
Author: User

[JAVA & #183; elementary]: 13. Interface
Definition

What is?

It is a set of standards, a set of rules, and a set of unified requirements for all classes.

What?

It appears to implement multi-inheritance.

What is there?

It contains only two ingredients:

1) public static constants.

2) abstract methods.

How to do it?

Use the interface keyword.

Format:

Public interface name {.....}

Known:

1) existing interfaces (provided by experts ).

2) custom interfaces (written by the programmer ).

 int obj1.compareTo(obj2 )

 

Note: compareTo must be used as the method name for object comparison. After comparison, compareTo must be an int integer.

And when the integer is greater than zero, it indicates that the former is greater than the latter;

If the integer is smaller than zero, it indicates that the former is smaller than the latter;

If this integer is equal to zero, it indicates that the former is equal to the latter.

However, the attributes of the two objects cannot be determined. Therefore, this method must be abstract.

Therefore, this method is as follows:

 public abstract intcompareTo( Object obj );

This method is abstract. According to the learned knowledge, the abstract method is either in the abstract class or in the interface.

Imagine: When the above compareTo () method is placed in an abstract class, the question is: Can all classes have an inheritance relationship with this abstract class?

Answer: No.

When the above compareTo () method is placed in the interface, the following question is: Can all classes have an inheritance (Implementation) Relationship with this interface?

Answer: Yes.

Because the rules for comparing objects can be formulated in advance, experts have prepared an interface java. lang. Comparable for programmers in advance.

The preceding abstract method is stored in [int compareTo (Object obj)].

How to implement interfaces?

Implemented by the implements keyword

Format:

Public class implements interface 1 {......}

 

Format:

Public class implements interface 1, interface 2 ,...{......}

 

Note: in Java, a class can implement either an interface or multiple interfaces.

Note: When a class implements an interface, this class must override all abstract methods from the interface. Otherwise, this class is an abstract class.

Application

Write a class to implement the given interface. At the same time, rewrite all abstract methods from interfaces in this class.

Finally, this class creates an object and calls the object method to solve the business. Complete.

1) import the import package. Interface Name; for example, import java. lang. Comparable;

2) Write a class to implement this interface; for example, public class Student implementsComparable {......};

3) rewrite the abstract methods from interfaces in this class; for example, override the compareTo () method;

4) Applications (write applications ).

Demo // student packagecom. hqg. oop. d39; // 1 import interface importjava. lang. comparable; importcom. hqg. oop. d38.a2. myDate; public classStudent extends Object implementsComparable {// 2 Implementation interface // 3 rewrite all abstract methods from the interface: The purpose is to make the Object of the current class have the ability to compare the size. @ Override public int compareTo (Object obj) {Student st2 = (Student) obj; if (this. score> st2.score) {return 1;} else if (this. score
 
  
0) {// exchange Student tem = stu [j]; stu [j] = stu [j + 1]; stu [j + 1] = tem ;}}}}}
 
Relatively abstract class

Abstract classes are used to represent the abstract concepts we have come up with in the analysis and design of problem domains. They are abstractions of a series of seemingly different but essentially identical specific concepts. interfaces, it is equivalent to a power outlet, and the pluggable component is equivalent to an electrical appliance. The key to component insertion is that there is a public interface and each component implements this interface. Interfaces are the key to component insertion.

(1) At the syntax layer, the Java language provides different definitions for abstract classes and interfaces. The following describes how to define an abstract class named Demo.

The Demo abstract class is defined as follows:

 

abstract classDemo { abstract voidmethod1(); abstract void method2(); … }

The Demo interface is defined as follows:

interface Demo { void method1(); void method2(); …}

In the definition of abstract classes, Demo can have its own data members or non-abstract member methods. In the definition of interfaces, Demo can only have static final data members, all member methods are abstract. In a sense, an interface is a special form of abstract class.

From the programming perspective, the inheritance rules of abstract classes and interfaces are different. abstraction only allows single inheritance, while a class can implement multiple interfaces. Interfaces support multiple inheritance. Secondly, in the definition of abstract classes, the default behavior of methods can be granted. In the definition of interfaces, methods cannot have default behaviors, the delegate must be used. In a sense, the interface is more abstract than the abstract class.

(2) At the design layer, abstract classes reflect an inheritance relationship in the Java language. To make the inheritance relationship reasonable, there must be A "Is-A" relationship between the parent class and the derived class, that is, the concept of parent class and Child class should be essentially the same. Otherwise, the interface does not require the implementer and interface definition to be consistent in concept, but only implement the interface definition contract. Consider this example. Suppose there is an abstract concept about the Door, the Door has two actions: open and close, in this case, we can use an abstract class or interface to define a type that represents the abstract concept. The definition methods are as follows:

The Door abstract class is defined as follows:

abstract classDoor { abstract voidopen(); abstract voidclose(); }

The Door interface is defined as follows:

interface Door { void open(); void close(); }

For other specific Door types, you can use an abstract class to define the Door or implements using the interface to define the Door. It seems that there is no big difference between using abstract classes and interfaces. If you want the Door to have the alarm function. The following describes possible solutions and analyzes them at the design layer.

Solution 1:

Add an alarm method to the Door definition as follows:

 

abstract classDoor { abstract voidopen(); abstract voidclose(); abstract voidalarm(); }

 

Or

 

interface Door { void open(); void close(); void alarm(); }

 

The AlarmDoor with alarm function is defined as follows:

 

class AlarmDoorextends Door { void open(){…} void close(){…} void alarm(){…} }

 

Or

 

class AlarmDoorimplements Door{ void open(){…} void close(){…} void alarm(){…} }

This method violates the interface isolation principle. In the Door definition, the behavior Methods inherent in the Door concept are mixed with the behavior methods of another concept "alarm. One problem is that the modules that rely solely on the Door concept will change with the concept of "alarm" (for example, modifying the parameters of the alarm method), and vice versa.

Solution 2:

Since open, close, and alarm belong to two different concepts, they should be defined in abstract classes that represent these two concepts according to the interface isolation principle. The two concepts are defined using abstract classes. Both concepts are defined using interfaces. One is defined using abstract classes, and the other is defined using interfaces.

Obviously, because the Java language does not support multiple inheritance, it is not feasible to define both concepts using abstract classes. The latter two methods are feasible, but their selection reflects the understanding of the concept nature in the problem field, and whether the reflection of the design intent is correct and reasonable.

If both concepts are defined using the interface method, there are two problems: first, we may not understand the problem field clearly. Is the concept of AlarmDoor actually a Door or an alarm? Second, if we have no problem with our understanding of the problem field, for example, through our analysis of the problem field, we find that AlarmDoor is essentially consistent with Door in concept, therefore, our design intent cannot be correctly revealed during implementation, because the definitions of these two concepts (both using interface-based definitions) do not reflect the above meaning.

If our understanding of the problem field is: AlarmDoor is essentially a Door in concept, it also has the alarm function. How can we design and implement it to clearly reflect what we mean? As mentioned above, abstract classes represent an inheritance relationship in Java, and the inheritance relationship Is essentially A "Is-A" relationship. Therefore, we should use abstract classes to define the concept of Door. In addition, AlarmDoor has the alarm function, indicating that it can complete the behaviors defined in the alarm concept. Therefore, the alarm concept can be defined through interfaces. As follows:

abstract classDoor{ abstract voidopen(); abstract voidclose(); } interface Alarm{ void alarm(); } class AlarmDoorextends Door implements Alarm{ void open(){…} void close(){…} void alarm(){…} }

This implementation method can clearly reflect our understanding of the problem field and correctly reveal our design intent. In fact, the abstract class represents the "Is-A" link, and the interface represents the "Has-A" link. It can be used as A basis for selection, of course, this is based on the understanding of the problem field. For example, if we think that AlarmDoor is essentially an alarm and has the Door function, then the above definition method will be reversed.

Abstract classes and interfaces are two methods of defining abstract classes in Java. They have great similarities. However, their choice often reflects the understanding of the concept nature in the problem field, and whether the reflection of design intent is correct and reasonable, because they represent the different relations between concepts. Only by correctly understanding the object-oriented design principles and using abstract classes and interfaces can an easy-to-use system be designed.

Business Philosophy

The emergence of interfaces greatly facilitates the work of our programmers, and the inheritance phenomenon can also be solved smoothly. In fact, interfaces give birth to life. When we get integrated, we feel the importance of interfaces in life, as well as programming.

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.