Javase Getting Started learning 21:java Object-oriented Interface (interface) (ii)

Source: Internet
Author: User

Multi-state of an interface implementation

In the previous post: Javase Introductory Learning 20:java Object-oriented Interface (interface) (i) mentions that the implementation of the interface is polymorphic, then

it A major analysis of the interface implementation of the polymorphic.

Instance One

Test.java Source file Code:

public class Test{public static void Main (string[] args) {//Implement interface Singersinger S1 = new Student ("Amy"); s1.sing (); S1.sleep () ; S1.study ();//Compile error//Implement interface Singersinger s2 = new Teacher ("Jack"); s2.sing (); S2.sleep (); S2.paint ();//Compile Error s2.eat ();// Compile error S2.teach ();//Compile error//Implement interface Painterpainter P1 = (Painter) s2;p1.paint ();p 1.eat ();p 1.teach ();//Compile Error p1.sing ();// Compile error P1.sleep ();//Compile Error}}//interface Singerinterface singer{//abstract method public void Sing ();p ublic void Sleep ();} Interface Painterinterface Painter {//abstract method public void paint ();p ublic void Eat ();} Student Class Student, inheriting a Singer interface class Student implements singer{//Private member variable private string name;//constructor method Student (String name) { THIS.name = name;} Public String GetName () {return name;} Student Class unique study () method public void study () {System.out.println ("Student is studying");} Override the Sing () method in interface singer public void Sing () {System.out.println ("Student is Singing");} Override the Sleep () method in interface singer public void sleep () {System.out.println ("Student is Sleeping");}} Teacher Class Teacher, inherits two interfaces Singer and interfaces Painterclass Teacher implements Singer,painter{//Private member variable private String name;//constructor teacher (String name) {this.name = name;} Public String GetName () {return name;} Teacher Class-Unique teach () method public void Teach () {System.out.println ("Teacher is Teaching");} Override interface singer Sing () method public void Sing () {System.out.println ("Teacher is Singing");} Override the Sleep () method of the interface singer public void sleep () {System.out.println ("Teacher is Sleeping");} Override the Paint () method of the interface painter public void paint () {System.out.println ("Teacher is painting");} Override interface Painter Eat () method public void Eat () {System.out.println ("Teacher is Eating");}}

Error in compiling process:



From the above error message can be seen: In the previous narrative object-oriented polymorphism when it said that the reference polymorphism and method polymorphism, as well as the multi-state of the citation

with type conversions, which are also in the interface can be implemented, but the difference is that an interface cannot be instantiated, but a reference to an interface can point to inheriting it

the child The object of the class, of course, is to invoke methods that are also subclasses of the abstract methods in the overridden interface. The specific object polymorphism can be referenced by:javase

Introductory learning 18:java Object-oriented polymorphism .

The number of rows in the above compilation process is 7, 13, 14, 15, 21, 22, 23. The types of these errors are missing symbols because the reference class

For example, the reference to the singer interface refers to the object S1 of the subclass student, and the object reference can contain only the overridden interface in the subclass student

Singer's two abstract methods cannot contain other methods that override the abstract methods in the painter interface and subclass student itself, and other classes

Like. To avoid this compilation error, we can create objects of subclass student and subclass teacher.

Example Two

Overwrite the code in the test class:

public class Test{public static void Main (string[] args) {//Create objects of Student class, Implement interface singerstudent S1 = new Student ("Amy"); S1.sing (); S1.sleep (); S1.study ();//Create an object of Teacher class, implement Interface singer and interface Painterteacher t1 = new Teacher ("Jack"); t1.sing (); T1.sleep (); T1.paint (); T1.eat (); T1.teach ();}}

Compile run Result:


Two usage of the interface (actual reference) (1) Streamline the program structure to eliminate duplication of definitions

For example, there are two classes with the same method, but the implementation function is different, you can define an interface, the method is extracted,

In a class that needs to use this method, it eliminates the hassle of multiple classes defining system methods.

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 that specifically describes the flight.

Is the definition of birds and insects, each of which has a way of flying, the class diagram is:


Defines an interface whose class diagram is as follows:


The specific code implementation:

Interface Flyanimalinterface flyanimal{//Abstract method Fly () void fly ();      }//Insect class insect{int legnum = 6;  void Oviposition () {};}      Bird class Bird {int legnum = 2;  void Egg () {}; }//Ant class Ant extends insect implements flyanimal{public void Fly () {System.out.println ("Ant Can Fly")      ;    } public void Oviposition () {System.out.println ("Ant can Spawn"); }}//Pigeon class Pigeon extends Bird implements flyanimal{public void Fly () {System.out.println ("Pigeon Can Fly      ");      } public void Egg () {System.out.println ("Pigeon can lay Eggs");          }} public class test{public static void Main (String args[]) {ant a=new ant ();         A.fly ();        A.oviposition ();  System.out.println ("Ant ' s legs is" + a.legnum);        System.out.println ("\ n");          Pigeon p= new Pigeon ();          P.fly ();  P.egg ();  System.out.println ("Pigeon s legs is" + p.legnum); }  }

Compile run Result:


(2) Expand program functions 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:


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 can induce

It has a common template, the "people" of the "food, accommodation" problem. At this point, the function of the interface can be played.

The specific implementation code is as follows:

interface      person{void Eat ();  void Sleep (); } class Student implements person{public void Eat () {System.out.println ("Students go to the cafeteria to eat!")      "); } public void Sleep () {System.out.println ("Students go to sleep in the dorm!")      "); }} class Teacher implements person{public void Eat () {System.out.println ("Teachers go to the Faculty restaurant for dinner!")      "); } public void Sleep () {System.out.println ("The teacher goes back to the school apartment to sleep!")      "); }} class parents implements person{public void Eat () {System.out.println ("parents go to the hostel restaurant for dinner!")      "); } public void Sleep () {System.out.println ("Parents go back to the guest house to sleep!")      ");     }} public class test{public static void Main (string[] args) {person P1 = new Student ();     P.eat ();        P.sleep ();     person P2 = new Teacher ();     P.eat ();       P.sleep ();     Person P3 = new parents ();     P.eat ();      P.sleep (); }  }  

Operation Result:


Now you need to add some features, namely now need to add "foreign guests, superior leader" two types of roles, and later tools need to add the appropriate identity corner

Colored People 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. This

Can show the function of the interface.

Our listing is shown in the update to:

Add the following two classes to the above program:

Class Foreign implements person{public      void Eat () {         System.out.println ("The foreign guests go to the hotel for dinner!") ");      }      public void Sleep () {         System.out.println ("The foreigner goes back to the hotel to sleep!") ");      }  }     Class Leader implements person{public      void Eat () {         System.out.println ("Leaders go to the hotel for dinner! ");      }      public void Sleep () {         System.out.println ("lead back to the hotel to sleep!") ");      }  }  

The code we added in the Main method is:

    Person P4 = new Foreign ();      P4.eat ();      P4.sleep ();        Person P5 = new Leader ();      P5.eat ();      

Operation Result:


Summarize

Javase Getting Started learning 21:java Object-oriented Interface (interface) (ii)

Related Article

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.