Java Programming Idea (vi)--Interface

Source: Internet
Author: User

The interface chapter talks about abstract class and interface, the abstract class feeling is very abstract in simple reading. And the interface of this chapter of the knowledge point, and did not like before the detailed, but also broken and difficult, there are several questions are several people in the seminar presented, before the polymorphic there is a domain problem is also the seminar was raised, that relatively easy to understand some.


1) Abstract class

Class tv{public      Void Show () {          System.out.println ("TV");      }  }    Class LeTV extends tv{public      Void Show () {          System.out.println ("LeTV");      }  }  Class MiTV extends tv{public      Void Show () {          System.out.println ("MiTV");      }  }  Class Santv extends tv{public      Void Show () {          System.out.println ("Santv");      }  }  public class Everytv {public      static void Tvshow (LeTV TV) {          tv.show ();      }      public static void Tvshow (MiTV TV) {          tv.show ();      }      public static void Tvshow (Santv TV) {          tv.show ();      }      public static void Main (string[] args) {          tvshow (new LeTV ());          Tvshow (New MiTV ());          Tvshow (New Santv ());      }  }

In fact, from the beginning of TV, there is no TV object created because the TV object doesn't make sense.

Java provides a mechanism for abstract methods, called pure virtual functions in C + +.

Classes that contain abstract methods are abstract classes, and if a class has one or more abstract methods, the class must be defined as an abstract class.

An abstract method declaration can have no method body. As follows:

Abstract show ();

Abstract class is not new, to ensure the purity of the abstract class, which is abstract class, in fact, this is a reason for the existence of abstract classes.

The above TV classes can be rewritten as abstract classes:

Abstract class tv{      abstract void Show ();  


Note that subclasses also need to inherit methods, and have method bodies.

In fact, TV is very abstract, TV itself does not need specific show method, specific TV has a specific implementation method, new TV This class is not useful, TV is an abstract concept.

Read an English answer--what is a abstract class, and when should it was used?

Talking about animals eat, animals are also an abstract level of the concept, but animals have the way to eat, each of the different animals have their own eating method, eat meat, eat grass, but must eat, animal this concept of things, can be declared as abstract class, if it is the ordinary class, then subclasses do not rewrite can also, Then the default becomes the same as the animal eat, but the animal itself does not eat, defined as abstract class, the abstract method needs to be implemented in the subclass, so extensibility, this should be the original intention of the designer.



2) interface

Public interface TV {}
if public is not defined, the interface only has access within the package, and the method of the interface is not declared public, and the interface can have fields, implicitly static and final.


Of course, we can completely design the TV as an interface. So why do you have an abstract class and an interface?

The interface has a specific place where the class implementing the interface must implement all the methods of the interface, except the abstract class, which can be implemented selectively. This question is summarized later in the answer.


3) Fully decoupled

Coupling is a concept of software engineering, the program design stresses high cohesion and low coupling, the coupling can be simply regarded as dependence, is the bond through tight.


The book first cited an example.

Class tv{    Public String name () {        return GetClass (). Getsimplename ();//Get class name    }        Object Show (object input) {         return input;   }}class LeTV extends tv{    String Show (Object input) {        return (String) input+ "in LeTV";    }}class MiTV extends tv{    String Show (Object input) {         Return (String) input+ "in MiTV";   }}public class TVShow {    public static void PLA Y (TV TV, Object O) {        System.out.println (Tv.name ());         System.out.println (Tv.show (o));   }    public static void Main (string[] args) {        TVShow ts = new TVShow ();         String mylove = "My Love TV show";        Ts.play (New LeTV (), Mylove);        Ts.play (New MiTV (), Mylove);    }}

Tvshow's Play method calls different methods according to the specific TV parameters received, which is called the- strategy mode .


Next there are computer, but the game is handled exclusively.

Class game{    private static int count;    Private final int id  = count++;    Public String toString () {        return ' Game ' +id;    }} public class computer{public    String name () {        return getclass (). Getsimplename ();//Get class name    }        Game Show (Game input) {        return input;    }} Class Lecomputer extends computer{    game show (game input) {        return input;    }} Class Micomputer extends computer{    game show (game input) {        return input;    }}

Although the book is a filter and processor example, but there is a little error in the book, although computer and TV have the same interface elements, but computer not inherit TV, is simply two classes, So it must be wrong for computer to work properly with the Tvshow play method. As can be seen in this example, the Tvshow method and the TV coupling are too tight, only support TV, what if Smart TV?


So, the TV is designed as an interface:

Public interface TV {String name (); Object Show (Object input);} public class TVShow {    public static void play (TV TV, Object o) {      &NB Sp System.out.println (Tv.name ());        System.out.println (Tv.show (o));    } public abstract class Abstracttv implements tv{    public String name () {  &nbsp ;     return GetClass (). Getsimplename ();      }    public abstract String Show (Object input);        public static void Main (string[] args) {& nbsp;       TVShow ts = new TVShow ();        String Mylove = "My Love TV show";        Ts.play (New LeTV (), mylove);    & nbsp;    Ts.play (New MiTV (), mylove);   }}class LeTV extends Abstracttv{    public String Show (Object input) {        return (String) input+ "in LeTV ";   }}class MiTV extends abstracttv{    public String Show (Object input) {         return (String) input+ "in MiTV";   }}

is not very troublesome, but also we have to create a new Abstracttv to implement the TV interface. What's the use of it? Look at the game change:

Class game{private static int count;    private final int id = count++;    Public String toString () {return ' Game ' +id;    }}class Computeradapter implements tv{private computer C;    Computeradapter (computer c) {this.c = C;    } public String name () {return c.name ();    Public Game Show (Object input) {return c.show (Game) input);  }}public class computershow{public String name () {return getclass (). Getsimplename ();//Get class name} Game    Show (Game input) {return input;        } public static void Main (string[] args) {Game G = new Game ();        Tvshow.play (New Computeradapter (New Lecomputer ()), g);    Tvshow.play (New Computeradapter (New Micomputer ()), g);    }}class Lecomputer extends computer{game show (game input) {return input;    }}class Micomputer extends computer{game show (game input) {return input; }}class computer{Public String name () {return getclass (). GetsimplEname ();//Get Class name} game show (game input) {return input; }}

Found no, originally can not give computer use of the Tvshow play method is now available, because Computeradapter realized the TV interface.


In fact, this mode is another design mode- adapter mode . Computeradapter receive different computer at the same time to implement the TV interface, in order to use the Tvshow method, otherwise the simple computer object can not be used as a method parameter, the adapter can be the interface you have to produce the required interface, that is, the interface of this example passed in, In fact, it is similar to the strategy model. Computeradapter itself is an agent, you only need to pass in the computer object, but not see the method inside the implementation.


There is also an interesting place, although all methods of implementing an interface, but Computeradapter and Abstracttv implement the Show method of the interface with a different type, the reason is on the object, If the show method of the TV interface is not the object type, but a specific one, then the method type must be the same when implementing the method.


The implementation of this interface is to reduce the coupling, tvshow can not only pass in the inherited Abstracttv object, for other implementations of the TV interface can also be used. Just start to see may be a little read, I read a long time, a lot of things, but finally understand.


4) Multiple Inheritance

Because only one class can be inherited, but it is possible to implement multiple interfaces, you have the functionality of multiple interfaces.

public class A extends B implements c,d,e{}


5) Domain of the interface

The fields placed on the interface are automatically static and final, and are also public. In fact, the characteristics in turn proved to be possible. There are also exercises.

Public interface T {    int a=1;} public class Test implements t{public    static void Main (string[] args) {        System.out.println (TEST.A);        System.out.println (test.a++);    }}

The static domain can be accessed directly through the class name, the final domain cannot be changed, and at the beginning of the JAVA5 there is an enumeration type.


Finally, as the book says, "Determining an interface is an ideal choice, so you should always choose an interface rather than a specific class." "This is actually luring.

Throughout, you will find that the interface is really abstract and abstract to be used in demand, not for use.

This is the same as the design pattern.






Java Programming Idea (vi)--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.