Interface (i)

Source: Internet
Author: User
Tags what interface

Interface

Interface, English is called interface, in software engineering, the interface refers to the method or function for others to call. From here, we can realize the original intention of the Java language Designer, which is the abstraction of the behavior. In Java, the form of an interface is as follows:

[Public] interface InterfaceName {}

The interface can contain variables and methods. Note, however, that the variables in the interface are implicitly specified as public static final variables (and can only be public static final variables, which are reported as compilation errors with private adornments), and methods are implicitly specified as public Abstract method and can only be public abstract method (with other keywords, such as private, protected, static, final and so on will be reported compile errors), and the interface of all methods can not have a concrete implementation, that is to say, The methods in the interface must all be abstract methods. From here we can see the difference between interface and abstract class, interface is an extremely abstract type, it is more "abstract" than abstract class, and generally does not define variables in the interface.

To have a class follow a specific set of interfaces requires the use of the Implements keyword, in the following format:

Class ClassName implements interface1,interface2,[....] {}

As you can see, a class is allowed to follow multiple specific interfaces. If a non-abstract class follows an interface, you must implement all the methods in that interface. Abstract methods in the interface may not be implemented for abstract classes that follow an interface.

 

Java is only support single inheritance, but there are multiple inheritance in the reality of this phenomenon, such as "Golden Monkey is an animal", The Golden Monkey inherit from the category of animals, while "golden Monkey is a valuable thing", the Golden Monkey from the "Valuable things" this class inheritance, while "Golden Monkey is a kind of things should be protected", Golden Monkey from The category "Things that should be protected" is inherited. In this way, the Golden Monkey can inherit from the three classes of "animal", "valuable things" and "things that should be protected", but since Java only supports single inheritance, golden monkeys inherit only one of the three classes and cannot inherit the three classes at the same time. So in order to encapsulate the multiple inheritance phenomena in real life, in order to realize multiple inheritance, we can encapsulate two of them into interfaces. Using interfaces can help us implement multiple inheritance.

  Interface is a special kind of abstract class, the abstract class contains only the definition of constants and methods, and there is no implementation of variables and methods.

Abstract class has some things interface can have, if an abstract class inside all the methods are abstract, there is no method need this abstract class to implement, and this abstract class inside all the variables are static (static) variables, are not change (final) variable, Such an abstract class can then be defined as an interface (interface). The format of defining a class as an interface is to replace the keyword class of the declaring class with the keyword interface of the declaration interface.

1/**2  * Define Interface 3 */4 public  interface Javainterfaces {5 6} in Java

   interface (interface) is a special kind of abstract class, in which all methods are abstract methods, and the attribute of this abstract class (that is, member variable) is declared as "public static final Type property name", and the default is declared as " public static final "that is, the member variables inside are common, static, and cannot be changed." Sowhen you declare constants inside an interface, you can write the form "public static final type constant name =value (value)" or "type constant name =value (value) "."For example, "public static final int id=10" can be directly written as "int id=10", because the default property declaration in the interface is "public static final", so "public static final" can omit to write.The abstract method declared in the interface can be identified without writing the abstract keyword, because all the methods inside the interface are abstract, so this "abstract"keywords are omitted by default, such as three methods declared in an interface: "public void Start ()", "public void Run ()", and "public void Stop ()", none of the three methods are identified with the abstract keyword before. But they are abstract methods, becauseThe method of declaration inside the interface is an abstract methodso the abstract method inside the interface willAbstract keyword omitted, because the default declaration of the method is abstract, so there is no need to write "abstract" word, which is different from the declaration of abstract methods in the abstract class, it is necessary to declare abstract methods in the abstract class must use the "abstract" keyword , and declaring an abstract method inside an interface can omit " abstract"。 Attention:The abstract method declared inside the interface is "public" by default"of, can only be "public" the reason is to amend the C + + in the case of multiple inheritance prone to problems, C + + inheritance is prone to problems, the problem is that more than one parent of multiple inherited classes if they have the same member variable, this reference will be quite troublesome, And when it runs, it produces a variety of problems. Java in order to fix this problem, all the member variables inside the interface are changed to static final, the member variable is the static type, then this member variable belongs to the entire class, rather than belong to an object. For multiple inheritance, there is actually more than one parent class object inside a subclass object, and for single inheritance there is only one parent object in the subclass object. Multiple inheriting subclass objects have more than one parent class object, and there may be duplicate member variables between these parent objects, which is very prone to problems, so the problem is avoided in Java, and the interface is used to implement multiple inheritance.as an interface, a class can inherit from the interface (or implement the interface), which is also multi-inheritance, the interface member variables are not exclusive to an object, are static member variables, belong to the entire class, so a class to implement multiple interfaces is irrelevant, there will be no conflicting objects between the problem. Implementation of multiple interfaces, but also to achieve multiple inheritance, but also to avoid multiple inheritance prone to problems, which is the use of interfaces to achieve multiple inheritance benefits.

Second, the interface characteristics

  

2.1. Interface examples
  1 package javastudy.summary; 2 3/** 4 * This defines the interface: Painter.  The two abstract methods of paint () and eat () are defined in the painter interface.  5 * 6 * @author GACL 7 * 8 */9 interface Painter {ten public void eat (); one public void paint (); 13 } 14 15/** 16 * This defines two interfaces: Singer defines the two abstract methods of Sing () and sleep () in the Singer interface. * * * * @author GACL */interface Singer {2 public void sing (); the public void Sleep ();   5} 26 27/** 28 * Class Student implemented Singer this interface * * * @author GACL * * * * + * Student implements Singer {34 The private String name;         Notoginseng public Student (string name) {this.name = name;-42} All in public String getName () return name; SetName (String name) {this.name = name; 47} 48 49/** 50 * Implementation interface      The Sing method defined in the * * * @Override the public void Sing () {si System.out.println ("Student is singing"); 55 } 56 57/** 58 * Implement the SLE defined in the interfaceEp Method (SYSTEM.OUT.PRINTLN) (63), public void sleep () {student-sleeping } study public void () {System.out.println ("studying ..."); The/** * Teacher This class implements two interfaces: singer and painter. Here teacher this class implements multiple inheritance by implementing two unrelated interfaces.  * GACL * @author * * * * * * * * * * * * * Teacher implements Singer, Painter {80 Bayi Public Teacher (String name) {this.name = name; 83} 84 85/** 86 * In the Teacher class rewrite the two interfaces inside the Abstract method, 87 * Implements the abstract method in both interfaces by overriding the abstract method.      * * * @Override Eat () {System.out.println ("Teacher is eating"); 92} 93 94         Public String GetName () {98 return name;] (+)-@Override-public void paint () {100 System.out.println ("Teacher is painting"), 101}102 103 public void SetName (String name) {104 THIS.name  = name;105}106 107 @Override108   public void Sing () {109 System.out.println ("Teacher is singing"),}111 @Override113 Public v OID sleep () {System.out.println ("Teacher is Sleeping"),}116 117 public void Teach () {118 S Ystem.out.println ("Teaching ..."); 119}120}121 122 public class Testinterfaces {123 124 public static void main (St         Ring[] (args) {125/**126 * This defines a variable for an interface type s1127 */128 Singer s1 = new Student ("le"); 129 S1.sing (); S1.sleep () 131 Singer s2 = new Teacher ("Steven"); S2.sing 133 . Sleep (); 134 Painter P1 = (Painter) s2;135 p1.paint (); 136 p1.eat (); 137}138}

Here, two rules are validated, " a class can implement multiple unrelated interfaces ," The teacher class implements both the singer interface and the painter interface, while the singer and painter interfaces are two interfaces that are not related to each other. " multiple unrelated classes can implement the same interface ", both the student class and the teacher class implement the singer interface, and the student class and the teacher class are not closely related to the two classes, which can be said to be unrelated to the two classes.

Operation Result:

2.2. Drawing memory analysis diagram experience polymorphism between interface and implementation classes

  

First, the first sentence of the main method is analyzed.

Singer S1 = new Student ("le");

Here first defines an interface type of variable S1, interface singer is implemented by the student class, that is, the equivalent of student class from the singer interface inheritance, singer interface is a special abstract class, so here Singer interface is the parent class of student class , so S1 is a reference to the parent class object, that is, the reference to a parent class object S1 to the subclass object Student after this sentence is executed. So the layout inside the memory should be like this: there is a reference to the parent class object in the stack space S1, in the heap space new out of a student object, the creation of this student object called Student Class construction method student (String name), It is defined as follows:

Student (String name) {

THIS.name = name;

}

By calling the construct method, the student object has its own name "le", so the Name property value of the student object inside the heap memory is "le".

This student object is able to access the sleep () method and The Sing () method located inside the code area, because the student class inherits from the parent class sing, so it is natural to have access to both methods, and in addition to the student class's Custom study () Method. So the code area contains these three methods waiting for the object of the student class to access, that is, to invoke. A normal student can call these three methods directly. So how do you find these three methods in the code area? There is a function pointer in the student object that can find this three method, and the reference object can find these three methods within the code area by pointing at the index of the pointer.

S1 is the index of the parent object, but at this point S1 is referring to the subclass object, which is the index of a parent object that points to the child class object. Unfortunately, because this S1 is a reference to a parent object, standing in the S1 angle, it is just a student of your sub-class object as a method pointer to the student () and sleep methods that SINGER,S1 can only see Sing objects. So using this S1 reference object only accesses the two methods of sleep () and sing () inherited from the parent class, but since these two methods are overridden in the subclass student, now is the case, the subclass student inherits from the parent class singer, In the subclass, the Sing () and sleep () methods inherited from the parent class are overridden, and the reference to the parent object is directed to the subclass object, and the three cases together make the polymorphism possible, so that when the method in the code area is called, Will invoke the method in the code area based on the actual object of new, so here in S1 's eyes, although this new student is considered a singer, this object is actually a student, so the reference to the parent object is used to S1 the call to sleep inside the code area ( ) and The Sing () method, the Sing () and sleep () methods that were overridden in the subclass are called.

Then analyze the second sentence.

Singer s2 = new Teacher ("Steven");

Teacher This class implements the singer interface and the painter interface, which is equivalent to inheriting from two parent classes, one parent class is singer, and the other parent class is painter.

  

The S2 Here is also a reference to the parent class object singer, which points to the subclass object teacher, and therefore a reference to the parent class object to the subclass object.

When creating this teacher object, call the teacher (String name) construction method, which is defined as follows:

Teacher (String name) {

This.name=name;

}

After calling the constructor method, teacher has his name Steven, so teacher's Name property value is Steven, because this teacher implements the painter interface and the singer interface, and therefore also inherits the methods inside the two interfaces, So a normal teacher can be accessed by: paint (), eat (), and sing (), sleep. The first two methods are inherited from the painter class, and the latter two are inherited from the singer class. In addition to these four methods, there is a teach () method of your own definition. Unfortunately, because S2 is a reference to a Singer class object, from the standpoint of S2, it only treats teacher as an ordinary singer, so it sees only the teacher () and sleep () methods in the Sing object, The teacher object is then called to find the two methods of sleep () and sing () located in the code area through the function pointers inside the objects. Other methods S2 are not visible, and therefore cannot be called.

Painter p1= (Painter) S2;

Here the S2 cast to Painter,s2 object is actually pointing to teacher, the S2 forced into painter, you can teacher as painter to use, so P1 will teacher as painter to see, So P1 can only see the painter () method and the Eat () method inside the teacher, so only these two methods can be accessed. So the interface for our actual objects, each interface exposes a part of the method of our actual object. What interface you use, you can only access the method defined in this interface, the method of other interface definition can not be accessed.

Interfaces can help us achieve this logic of multiple inheritance, where there is polymorphism between the interface and its implementation classes.

2.3. Verify the further features of the interface through the following code
  1 package javastudy.summary; 2 3/** 4 * Define the "valuable things" class as an interface valuable.  An abstract method is defined in the interface Getmoney () 5 * @author GACL 6 * 7 */8 interface Valuable {9 public double Getmoney (); 10} 11 12/** 13 * The "What should be protected" class is defined as an interface protectable. 14 * Defines an abstract method beprotected () inside the interface; * @author GACL * * * * */interface protectable {23 public void beproteced (); 20} 21 22/** * * This is the interface and interface The inheritance between interface a inherits the interface protectable, 24 * Thus naturally inherits the abstract method inside the interface protectable beprotected (). 25 * Therefore, a class to implement interface A, in addition to implementing the abstract method defined in interface A (), 26 * Also to implement interface a from its parent interface inherited from the abstract method beprotected (). 27 * Interface A is implemented only if both of these abstract methods are implemented. * @author GaCl */Interface A extends Protectable {33} 34 35/** 36 * This defines an abstract class Anim Al Panax Notoginseng * @author GACL * * * * * * * 43 * * + abstract class Animal {$ private String name; 42/**-The Animal class declares a An abstract method enjoy () () () */enjoy abstract void (); 46} 47 48/** 49 * Here is to achieve our original semantics: 50 * "Golden Monkey is an animal" at the same time "he is also a valuable thing" at the same time, "he is also should be protected things." And the definition of a class GoldenmOnKey. 51 * In order to implement the above semantics, the "valuable things" class is defined as an interface valuable, 52 * the "What should be protected" class is also defined as an interface protectable. This allows for multiple inheritance. The Goldenmonkey class first inherits from the animal class and then goldenmonkey the class to implement the valuable interface and the Protectable interface, 54 * This allows the Goldenmonkey class to be implemented at the same time from the animal class, Valuable class, Protectable class inherited, that is, the implementation of multiple inheritance, 55 * To achieve the original semantics.      GACL * @author * * * * */Goldenmonkey extends Animal implements Valuable,protectable {60 61/** 62 * In the Goldenmokey class rewrite the interface protectable inside the beprotected () This abstract method, 63 * Implementation of the interface protectable. * */@Override beproteced () {System.out.println ("live in the") {68} 69 70/** 71 * In the Goldenmokey class rewrite the interface valuable inside the Getmoney () This abstract method, the implementation of the interface valuable. * * * @Override the public double Getmoney () {10000; 76} 77 78/** 79 * This Rewrite the abstract method inherited from the abstract class animal enjoy (). 80 * Implementation of this abstract method, but here is an empty implementation, empty implementation is also an implementation. Bayi */@Override enjoy void () () {+) {88/** 89 * Actually in memory we new is the Golden Monkey, in the Golden Monkey there are many methods, 90 * But the interface Reference Object v can see only in the interface valuable inside the declaration of Getmoney ( ) method, 91 * Therefore, you can use V.getmoney () to invoke the method. Other methods of V are not visible, and nature is not called. * * * Valuable v = new Goldenmonkey (); 94 System.out.println (V.getmoney ()); 95/** 96 * Cast v into P, equivalent to a window, through this window can only see the interface protectable inside the beprotected () method */98 Prote CTable p = (protectable) v;  P.beproteced (); 100} 101}102 103/**104 * Here let the hen class to implement interface A, interface A is also inherited from the interface protectable, interface a itself defines an abstract method M (), 105 * So this is the equivalent of two abstract methods in interface A: M () and beprotected (). 106 * So the hen class is going to implement interface A, it is necessary to rewrite the two abstract methods in a, the implementation of these two abstract methods after the implementation of interface A.         107 * @author gacl108 *109 */110 class Hen implements A {111 @Override113 public void beproteced () {114 }116 117 @Override118 public void M () {119}121 122}123 124/**125 * interface defined in Java 1 */127 public class Javainterfacestest {129 public static void main (string[] args) {130        Goldenmonkey.test (); 131}132} 

Interface Summary: interfaces and interfaces can inherit from each other, classes and classes can inherit from each other, classes and interfaces can only be classes to implement the interface .

Interface (i)

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.