"Java Learning Note 22" Parsing interface usage and example analysis in Java inheritance

Source: Internet
Author: User

First, the definition

Java Interface (Interface), is a series of methods of the Declaration, is a collection of methods features, an interface only the methods of the characteristics of the method is not implemented, so these methods can be implemented in different classes, and these implementations can have different behavior (function).

The general form of the interface definition is:

[Access control character]interface < interface name > {

Type identifier final symbol constant name n = constant;

Returns the value type method name ([parameter list]);

...

}

Second, the characteristics of the interface

1. The member variables in the Java interface are public,static,final by default (all can be omitted) and must be displayed initialized, that is, the member variables in the interface are constant (uppercase, the words are separated by "_")

2, the Java interface method is the default public,abstract type (can be omitted), there is no method body, cannot be instantiated

3. The Java interface can only contain member variables of type public,static,final and member methods of type Public,abstract

4, there is no construction method in the interface, cannot be instantiated

5, one interface cannot implement (implements) another interface, but it can inherit many other interfaces

6. The Java interface must implement its abstract method through a class

7. When a class implements a Java interface, it must implement all the abstract methods in the interface, otherwise the class must be declared as an abstract class

8, the creation of an instance of an interface (instantiation) is not allowed, but it allows to define a reference variable of the interface type that references an instance of the class that implements the interface

9, a class can only inherit a direct parent class, but can implement multiple interfaces, the indirect implementation of multiple inheritance.

Third, the use of the interface

1, streamline the program structure, exempt from duplicate definition

For example, there are two classes with the same method, but the implementation function is not the same, you can define an interface, the method is refined, in the need to use the method of the class to implement, it is exempt from multiple classes to define the system method of trouble.

For example: Birds and insects have the function of flying, this function is the same, but other functions are different, in the process of implementation of the program, you can define an interface, specifically describe the flight.

Is the definition of birds and insects, each of which has a way of flying.

Defines an interface whose class diagram is as follows:

The implementation code is as follows:

1 interface   flyanimal{    2    void Fly (); 3} 4 class   insect {    5    int  legnum=6; 6} 7 class  Bir d {    8   int  legnum=2; 9   void Egg () {};10}11 class Ant Extendsinsect implements  flyanimal {    public void Fly () {        System.out.println ("Ant can  Fly"),    }15}16 classpigeon  extends Bird Implements  Flyanimal {public    void Fly () {        System.out.println ("Pigeon  Can Fly");    }20 Public    Void Egg () {        System.out.println ("Pigeon  can lay  eggs"),    }23}24 Public classinterfacedemo{25 public    static void Main (String args[]) {+      ant a=new ant ();      a.fly ();      System.out.println ("Ant ' s legs is" + a.legnum);      Pigeon p= New Pigeon (); P.fly (     );      P.egg (); 32   }33}

Program Run Result:

Ant can Fly

Ant ' Slegs is 6

Pigeon Can Fly

Pigeon can lay eggs

Second, expand the program function to respond to changes in demand.

Assuming a school reception process, entertain different identities of people's accommodation problems, the corresponding rules are as follows:

Identity

Food

Homestays

Students

Canteen

Dormitory

Teachers

Teacher Canteen

School Apartments

Student Parents

Hostel

Hostel

Theoretically, it is possible to define a corresponding class for each person of different identities, and to implement the respective methods, but observing the writing class, we can conclude that there is a common template, that is, "people" of the "food, accommodation" problem. At this point, the function of the interface can be played. The implementation code is as follows:

 1 interfaceperson{2 void Eat (), 3 void Sleep (), 4} 5 6 class studentimplements person{7 public void Eat ( {8 System.out.println ("Students go to the cafeteria to eat!") "); 9}10 public void sleep () {One System.out.println ("Students go to sleep in the dorm!") ");}13}14 class teacherimplements person{16 public void Eat () {System.out.println (" Teachers go to the Faculty restaurant for dinner! ") }19 public void Sleep () {System.out.println ("The teacher goes back to the school apartment to sleep!") ")}22}23 class parents implements Person{24 Publicvoid eat () {System.out.println (" parents go to the hostel restaurant for dinner! ") }27 public void Sleep () {System.out.println ("Parents go back to the guest house to sleep!")                    ");}30}31 public class personinterface{33 public static void Main (string[] args) 34 {35 Person P=new Student (); P.eat (); PNs p.sleep (); p            =new Teacher (); P.eat (); P.sleep (); p=new parents (); 42        P.eat (); P.sleep (); 44}45} 

Program execution Results:

Students go to the cafeteria to eat!

Students go to sleep in the bedroom!

Teachers to the staff restaurant to eat!

Teacher back to school apartment to sleep!

Parents go to the hostel restaurant to eat!

Parents back to the guest house to sleep!

Now you need to add some features, namely now need to add "foreign guests, superior leadership" two types of roles, and later tools need to add the appropriate role of the person to come in, at this time, only need to add the "foreign guests" class, "Leader" class, and the main class can still be used, no need to make more changes. At this point, you can show the function of the interface.

Add the following two classes to the above program.

1 class Foreign implements person{2     publicvoid Eat () {3        System.out.println ("The foreign guests go to the hotel for dinner!") "); 4     } 5 public     void Sleep () {6        System.out.println ("The foreigner goes back to the hotel to sleep!") "); 7     } 8} 9  class Leader implements PERSON{11     Publicvoid eat () {        System.out.println ("Leaders go to the hotel for dinner!") ");     }14 public     Void Sleep () {        System.out.println (" The foreign guest goes back to the hotel to sleep! ") ");     }17}

The use of the main function is still the same.

The complete code is given below:

 1 interfaceperson{2 void Eat (), 3 void Sleep (), 4} 5 6 class studentimplements person{7 public void Eat ( {8 System.out.println ("Students go to the cafeteria to eat!") "); 9}10 public void sleep () {One System.out.println ("Students go to sleep in the dorm!") ");}13}14 class teacherimplements person{16 public void Eat () {System.out.println (" Teachers go to the Faculty restaurant for dinner! ") }19 public void Sleep () {System.out.println ("The teacher goes back to the school apartment to sleep!") ")}22}23 class parents implements Person{24 Publicvoid eat () {System.out.println (" parents go to the hostel restaurant for dinner! ") }27 public void Sleep () {System.out.println ("Parents go back to the guest house to sleep!") ");}30}31 class Foreign implements Person{32 Publicvoid eat () {System.out.println (" The foreign guests go to the hotel to eat! ") ");}35 public void Sleep () {System.out.println (" The foreigner goes back to the hotel to sleep! ") }39}38 Leader implements person{41 Publicvoid eat () {System.out.println ("The leader goes to the hotel for dinner!") ")}44 public void Sleep () {System.out.println (" leaderBack to the hotel to sleep!                    ");}47}48-public class PERSONINTERFACE{50 public static void Main (string[] args) 51 {52 Person P=new Student (); P.eat (); P.sleep (); p                    =new Teacher (); P.eat (); P.sleep (); p=new parents (); 59 P.eat (); P.sleep (); p=new Foreign (); P.eat ()                    ; P.sleep (); p=new Leader (); P.eat (); 66 P.sleep (); 67}68}

Program execution Results:

Students go to the cafeteria to eat!

Students go to sleep in the bedroom!

Teachers to the staff restaurant to eat!

Teacher back to school apartment to sleep!

Parents go to the hostel restaurant to eat!

Parents back to the guest house to sleep!

The foreign guests to the hotel to eat!

The foreign guests go to the hotel to sleep!

The leader went to the hotel for dinner!

Head back to the hotel to sleep!

Example two:

It is used to calculate the time required for each vehicle to run 1000 km, and it is known that the parameters of each vehicle are 3 integers a, B, and C expressions. There are two types of tools available:

Car and plane, wherein car's speed operation formula is: A*B/C

The speed of Plane is calculated as: A+b+c.

If you add a 3rd type of transport, such as a train (Train), you do not have to modify any of the previous programs, only the process of writing a new vehicle.

 1 Import java.lang.*;  2 interface Common {3 double Runtimer (doublea, double b, double c); 4 String getName ();//Get the name of the vehicle 5} 6 7 class Plane Implementscommon {8 public doubleruntimer (double A, double b, double c) {9 retur N (A + B + C),}11 public String getName () {"Plane";}14}15 cl Implements Common {1 public doubleruntimer (double A, double b, double c) {n-return (A*B/C) 8}19 public String GetName () {return "Car",}22}23, public class C Omputetime {+ public static void Main (stringargs[]) {double a=3;28 double b=5;2 9 Double c=6;30 double v,t;31 commond=new Car (); v=d.runt Imer (a,b,c), t=1000/v;34 System.out.println (d.getname () + "average speed:" +v+ "km/h"); .Out.println (D.getname () + "Run Time:" +t+ "hours"); D=newplane (); PNs V=D.R Untimer (10,30,40); t=1000/v;39 System.out.println (D.getname () + "average speed:" +v+ "km/h" ); System.out.println (D.getname () + "Run Time:" +t+ "hours"); 41}42}

The result of the program operation;

Average speed of car: 2.5 km/h

Car Running time: 400.0 hours

Average speed of plane: 80.0 km/h

Operating time of plane: 12.5 hours

"Java Learning Note 22" Parsing interface usage and example analysis in Java inheritance

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.