[Java primary]:13. Interface

Source: Internet
Author: User
Tags comparable

definition

What is?

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

Do what?

It is to achieve multiple inheritance and appear.

What do you got?

It consists of only two ingredients:

1) The static constants of the public.

2) Abstract method.

How to do?

Implemented by interface keywords.

Format:

<span style= "FONT-SIZE:18PX;" ><span style= "FONT-SIZE:18PX;" >public interface interface Name {...} </span></span>

Known for:

1) existing interfaces (provided by experts).

2) Custom interfaces (written by programmers themselves).

<span style= "FONT-SIZE:18PX;" ><span style= "FONT-SIZE:18PX;" > int Obj1.compareto (OBJ2) </span></span>

Rule: Object compare size must use CompareTo as the method name, the result of comparison size must be an int type integer.

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

When this integer is less than zero, the former is less than the latter;

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

However, the two objects are not currently determined by what attributes they are compared. Therefore, this method must be abstract.

Therefore, this method is as follows:

<span style= "FONT-SIZE:18PX;" ><span style= "FONT-SIZE:18PX;" > Public abstract Intcompareto (Object obj);</span></span>

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

Imagine: When the above CompareTo () method is placed in an abstract class, Q: Can all classes inherit from this abstract class?

Answer: Negative.

When the above CompareTo () method is placed in the interface, Q: Can all classes inherit (implement) relationships with this interface?

Answer: Yes.

Because the rules for object comparison can be developed in advance, the expert prepares an interface java.lang.Comparable for programmers in advance, where

The above abstract method is stored [int compareTo (Object obj)]

How do I implement an interface?

Keyword implements keywords to achieve

The format is:

<span style= "FONT-SIZE:18PX;" ><span style= "FONT-SIZE:18PX;" > public class  implements  interface 1 {...} </span></span>

The format is:

<span style= "FONT-SIZE:18PX;" ><span style= "FONT-SIZE:18PX;" >public class  implements  interface 1, interface 2, ... { ...... } </span></span>

Note: In Java, a class can implement an interface without implementing it, or it can implement only one interface and multiple interfaces.

Note: When a class implements an interface, the 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, all abstract methods from the interface are overridden in this class.

Finally, this class goes to create objects, invoking the object's methods to solve the business. Complete.

1) Imports import package. Interface name; such as: Import java.lang.Comparable;

2) write the class to implement this interface; such as: public class Student implementscomparable {...} ;

3) In this class, rewrite the abstract method from the interface; such as: Rewrite the CompareTo () method;

4) Apply (write application).

<span style= "FONT-SIZE:18PX;" ><span style= "FONT-SIZE:18PX;" >demo//Student Class packagecom.hqg.oop.d39;  1 Import interface importjava.lang.Comparable; Importcom.hqg.oop.d38.a2.MyDate;       Public Classstudent extends Object implementscomparable {//2 implements an interface//3 overrides all abstract methods from an interface: The goal is to have the ability to compare the size of objects in the current class.                           @Override public int compareTo (Object obj) {Student st2 = (Student) obj;              if (This.score > St2.score) {return 1;              }else if (This.score <st2.score) {return-1;              }else{return 0;              }//return-(This.score-st2.score); /** * 1) basic types of data compare equal with = =, compare size with relational operator * 2) reference type Data compare equal with Equals () method, compare size with Co               Mpareto () method.                           * * *///return This.name.compareTo (st2.name); return-(this. Sex+ ""). CompareTo (St2.   sex+ "");                        int x = (this. Sex+ ""). CompareTo (St2.              sex+ "");              int y =-(This.score-st2.score);              if (x = = 0) {return y;              }else{return x;              } String S1 =this.getbirthday (). toString ();              String S2 =st2.getbirthday (). toString ();                    return S1.compareto (S2);       }//instance variable private String name;       Private Final Boolean SEX;              Private MyDate birthday;             private int score;              Constructor public Student () {int n = (int) (2 * math.random ()); This.       SEX = n = = 1;              } public Student (String name, Mydatebirthday, int. score) {this ();              THIS.name = name;              This.birthday = Birthday;       This.score = score;  } public Student (String name, Boolean sex,mydate birthday, int score) {this.name = name;            sex = sex;              This.birthday = Birthday;       This.score = score;       } public String GetName () {return name;       } public void SetName (String name) {this.name = name;       } public mydate Getbirthday () {return birthday;       } public void Setbirthday (mydate birthday) {this.birthday = birthday;       } public int Getscore () {return score;       } public void SetScore (int score) {This.score = score;       } public boolean Issex () {return SEX; } @Override Public String toString () {return ' "+ name +" + (SEX? ")       Male ":" female ") +" + Birthday + "" + score; }}package com.hqg.oop.d39;  Importjava.util.Arrays; Expert-given tool class, used to implement array sorting importcom.hqg.oop.d38.a2.MyDate; Public ClassQuTest5 {public static void main (string[] args) {student[] ss = new student[5];              Ss[0] = new Student ("Zhang Mowgli", New MyDate (1992, 10, 11), 650);              SS[1] = new Student ("Zhao", False, New MyDate (1992, 5, 15), 680);              SS[2] = new Student ("Wei-Smile", New MyDate (1993, 1, 31), 670);              SS[3] = new Student ("Spider", True, New MyDate (1992, 9, 10), 660);                           SS[4] = new Student ("Zhou Zhijo", False, New MyDate (1993, 2, 7), 700);              SYSTEM.OUT.PRINTLN ("The initial state of five pupils is as follows:");              System.out.println ("============================");              SYSTEM.OUT.PRINTLN ("Name Gender Birth date Entry");              System.out.println ("============================");                     for (Student tem:ss) {System.out.println (TEM);              System.out.println ("----------------------------");                           }//Business 1: All students rank arrays.sort (ss) in ascending order of entry grades;              System.out.println ("\ n \ nthe five students by entry grade ascending as follows:"); System.out.println ("============================");              SYSTEM.OUT.PRINTLN ("Name Gender Birth date Entry");              System.out.println ("============================");                     for (Student tem:ss) {System.out.println (TEM);              System.out.println ("----------------------------");              }//Business 2: Entry grades descending order//reverse the value in the CompareTo () method Descending//Business 3: Sort by name              Change the return value in the CompareTo () method to the value after the name comparison.              Business 4: Gender Classification//Boolean type cannot compare size, convert it to other types of data and then compare. Business 5://Compound condition sort//Business 6: Sort by date of birth}} class Arrays {public static void sort (student[] Stu)  {for (int i = 0; I <stu.length-1;  i++) {for (int j = 0; J <stu.length-i-1;                                                       J + +) {int re =stu[j].compareto (stu[j+1]);//Two students compare size, results stored in re                          if (Re > 0) {         Exchange Student tem =stu[j];                                   STU[J] =stu[j+1];                            Stu[j+1] =tem; }}}}}</span></span>

more Abstract Classes

The so-called abstract class is used to characterize our analysis in the problem domain, the abstract concept of design, is a series of seemingly different, but essentially the same specific concept of abstraction; the so-called interface, the equivalent of a power outlet, pluggable components equivalent to electrical appliances. The key to pluggable artifacts is that there is a common interface and that each component implements this interface. Interface is the key to realize the pluggable nature of the component.

(1) From the syntactic level, the Java language for abstract classes and interfaces give different definitions, the following to define a named demo of the abstract class as an example to illustrate this difference.

The demo abstract class is defined in the following way:

<span style= "FONT-SIZE:18PX;" ><span style= "FONT-SIZE:18PX;" >abstract Classdemo {abstract voidmethod1 (); abstract void method2 (); ...} </span></span>

The demo interface is defined in the following way:

<span style= "FONT-SIZE:18PX;" ><span style= "FONT-SIZE:18PX;" >interface Demo {void method1 (); void Method2 (); ...} </span></span>

In the definition of abstract class, the demo can have its own data members, but also can have non-abstract member methods, and in the definition of the interface, the demo can only have static final data members, all the member methods are abstract. In a sense, an interface is a special form of abstract class.

From a programmatic point of view, first of all, abstract classes and interface inheritance rules are different, abstract only allow single inheritance, and a class can implement multiple interfaces. Interface for the support of multiple inheritance; second, in the definition of an abstract class, the default behavior of the method can be given, whereas in the definition of an interface, the method cannot have the default behavior, the delegate must be used, and in a sense, the interface is more abstract than the abstract class.

(2) from the design level, abstract classes in the Java language embodies an inheritance relationship, in order to make the inheritance relationship reasonable, there must be a "is-a" relationship between the parent class and the derived class, that is, the parent class and subclass in the concept should be the same in nature. In the case of interfaces, the interface does not require that the implementation and interface definitions are inherently consistent in concept, but only the contract that implements the interface definition. Consider an example where, assuming there is an abstract concept about door, the door has the ability to execute two actions open and close, at which point we can define a type that represents the abstract concept by means of an abstract class or interface, as follows:

Door abstract classes are defined in the following way:

<span style= "FONT-SIZE:18PX;" ><span style= "FONT-SIZE:18PX;" >abstract Classdoor {abstract voidopen (); abstract voidclose ();} </span></span>

The interface of the door is defined in the following way:

<span style= "FONT-SIZE:18PX;" ><span style= "FONT-SIZE:18PX;" >interface Door {void open (); void close ();} </span></span>

Other specific door types can be extends using door defined by an abstract class or implements door defined using an interface method. It seems that there is no big difference between using abstract classes and interfaces. If you now require door also have the function of alarm. The possible solutions are listed below, and the scenarios are analyzed from the design level.

Solution One:

Simply add a alarm method to the definition of door, as follows:

<span style= "FONT-SIZE:18PX;" ><span style= "FONT-SIZE:18PX;" >abstract Classdoor {abstract voidopen (); abstract voidclose (); abstract voidalarm ();}</span></span>

Or

<span style= "FONT-SIZE:18PX;" ><span style= "FONT-SIZE:18PX;" >interface Door {void open (); void close (); void alarm ();}</span></span>

Then the Alarmdoor with alarm function is defined as follows:

<span style= "FONT-SIZE:18PX;" ><span style= "FONT-SIZE:18PX;" >class alarmdoorextends Door {void open () {...} void close () {...} void alarm () {...}} </span></span>

Or

<span style= "FONT-SIZE:18PX;" ><span style= "FONT-SIZE:18PX;" >class alarmdoorimplements door{Void Open () {...} void close () {...} void alarm () {...}} </span></span>

This method violates the principle of interface isolation, and in the definition of door, it mixes the behavior method inherent in the door concept with another concept of "alarm". One problem is that modules that rely solely on the concept of door are changed by the concept of "alarm" (e.g., modifying the parameters of the alarm method) and vice versa.

Solution Two:

Since open, close and alarm belong to two different concepts, they should be defined separately in an abstract class that represents both concepts, based on the principle of interface isolation. These two concepts are defined using an abstract class approach, both of which are defined using an interface approach, one that is defined using an abstract class approach, and another that is defined using an interface approach.

Obviously, because the Java language does not support multiple inheritance, it is not feasible for both concepts to be defined using abstract class methods. The latter two methods are feasible, but the choice of them reflects the understanding of the conceptual nature of the problem domain and the correctness and reasonableness of the design intent.

If both concepts are defined using an interface approach, two questions are reflected: first, we may not understand the problem areas clearly, alarmdoor the concept is essentially door or alarm? Second, if we have no problem with our understanding of the problem areas, for example: we find that Alarmdoor is consistent in concept and door by analysis of the problem domain, then we do not have the right to reveal our design intent when we implement it. Because the definitions of both concepts, which are defined using interface methods, do not reflect the above meanings.

If our understanding of the problem area is: Alarmdoor is inherently door in concept, and it has a function of alerting. How do we design and implement to clearly reflect what we mean? As already mentioned, abstract classes represent an inheritance relationship in the Java language, and the inheritance relationship is essentially a "is-a" relationship. So for the concept of door, we should use the abstract class approach to define it. In addition, Alarmdoor also has the alarm function, indicating that it can complete the alarm concept defined behavior, so the alarm concept can be defined by the interface method. As shown below:

<span style= "FONT-SIZE:18PX;" ><span style= "FONT-SIZE:18PX;" >abstract classdoor{abstract Voidopen (); abstract voidclose ();} interface alarm{void Alarm ();} class Alarmdoorexten DS Door implements alarm{Void Open () {...} void close () {...} void Alarm () {...}} </span></span>

This kind of realization basically can clearly reflect our understanding of the problem area, and reveal our design intention correctly. In fact, the abstract class represents the "is-a" relationship, interface represents the "has-a" relationship, in the choice can be used as a basis, of course, this is based on the understanding of the problem areas, such as: if we believe that alarmdoor in the concept is essentially an alarm, but also has Door function, then the above definition will be reversed.

Abstract classes and interfaces are two ways of defining abstract classes in the Java language, and there is a great similarity between them. However, the choice of them often reflects the understanding of the conceptual nature of the problem areas, the correctness and reasonableness of the design intent, as they represent the different relationships between the concepts. Only by correctly understanding object-oriented design principles and using abstract classes and interfaces flexibly can we design an easy-to-use system.

Business Ideas

The appearance of the interface is greatly convenient for us to change the programmer's work, multi-inheritance phenomenon can also be solved smoothly. In fact, the interface conceived in life, a little experience, feel the importance of the interface in life, in programming is also the case.





[Java primary]:13. Interface

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.