Java Programming Ideas Learn note 9

Source: Internet
Author: User
Tags export class

Nine, interface

Interfaces and internal classes provide us with a more structured approach to separating interfaces from implementations.

1. Abstract classes and abstract methods

Abstract classes are a kind of moderation between common classes and interfaces. Creating an abstract class is what you want to manipulate a series of classes through this generic interface.

Java provides a mechanism called an abstract method , which is incomplete, with only declarations and no method bodies. Cases:

  abstract void f ();

Classes that contain abstract methods are called abstract classes.

If you inherit from an abstract class and want to create an object of that new class, you must provide a method definition for all the abstract methods in the base class. If you do not do so, the export class is also an abstract class.

We may create an abstract class that does not have any abstract methods. Consider this: it would be useful to have a class that contains any abstract method that does not make sense, and we want to block any object that produces the class.

2. Interface

  The abstract keyword allows people to create one or more methods in a class that do not have any definition-providing an interface section, but not providing any corresponding concrete implementations that are created by inheritors of this class. interface This keyword produces a completely abstract class that does not provide any concrete implementation at all. It allows the creator to determine the method name, the argument list, and the return type, but there is no method body. The interface provides only the form, without providing any specific implementation.

An interface says, "So the class that implements the particular interface looks like this." The interface is used to establish the protocol between classes.

However,interface is not only an extremely abstract class, because it allows people to implement some kind of multiple secondary variant by creating a type that can be transformed upward into multiple base classes.

An interface can also contain fields, but these fields are implicitly static and final .

To have a class follow a particular interface, you need to use the implements keyword, which says "interface is just the way it looks, but now I want to state how it works." ”

The methods in the interface are implicitly defined as public , so when an interface is implemented, the method defined in the interface must be defined as public.

3. Complete decoupling  

This class and its subclasses can only be used if a method operates on a class other than an interface. If you want to apply this method to a class that is not in this inheritance structure, you will encounter obstacles. Interfaces can largely relax this limitation, so it allows us to write code that is more reusable.

Creating a method that can behave differently depending on the parameter object being passed is called a policy design pattern. such methods contain fixed portions of the algorithm to be executed, and "policy" contains the changed parts. A policy is a parameter object that is passed in, which contains the code to execute.

  Adapter design mode , the code in the adapter will accept the interface you have and produce the interface you need.

Multiple inheritance in 4.Java

Any number of interfaces can be inherited and can be transformed upward into each interface.

The core reason for using interfaces is to be able to move up to multiple base types (and the resulting flexibility). However, the second reason for using an interface is the same as using an abstract class: Prevent the client programmer from creating objects of that class, and make sure that this is just an interface.

If you want to create a base class without any method definitions and member variables, you should select an interface instead of an abstract class. In fact, if you know that something should be a base class, then the first choice should be to make it an interface.

5. Extending the interface through inheritance

With inheritance, new method declarations can be easily added to the interface. You can also combine several interfaces in a new port through inheritance. In both cases, a new interface can be obtained.

  ① clash of names when combining interfaces

When implementing multiple interfaces with the same name method, but their signature or return type is different, there is confusion, so try to avoid this situation.

6. Adapter interface

One of the most appealing reasons for interfaces is to allow multiple, different implementations of the same interface. In a simple case, its embodiment is usually a method that accepts an interface type, and the implementation of the interface and the object passed to the method depend on the consumer of the method.

Therefore, a common use of interfaces is the policy design pattern, when you write a method that performs some action, and the method will accept an interface that you specify as well. You are basically declaring: "You can call my method with any object you want, as long as your object follows my interface." ”

7. Domains in the interface

Because any domain that is placed into the interface is automatically static and final , the interface becomes a convenient tool for creating constant groups. These fields are not part of the interface, and their values are stored in the static storage area of the interface.

With Java SE5, there's no point in using interfaces to group constants, because we have the enum keyword.

8. Nested Interfaces  

Interfaces can be nested within a class or in other interfaces.

classA {InterfaceB {voidf (); }     Public classBimp implements B { Public voidf () {}}Private classBIMP2 implements B { Public voidf () {}} Public InterfaceC {voidf (); }    classCimp implements C { Public voidf () {}}Private classCIMP2 implements C { Public voidf () {}}InterfaceD {voidf (); }    Private classDimp implements D { Public voidf () {}} Public classDIMP2 implements D { Public voidf () {}} PublicD getd () {return Newdimp ();} PrivateD DRef;  Public voidReceiveD (d d) {DRef=D;    DREF.F (); }}InterfaceE {InterfaceG {voidf (); }     Public InterfaceH {voidf (); }    voidg (); //cannot create a private interface//private interface I {}} Public classnestinginterfaces { Public classBimp implements A.B { Public voidf () {}}classCimp implements A.C { Public voidf () {}}//cannot implement a private interface//class Dimp implements A.D {//Public void F () {}// }    classEimp implements E { Public voidg () {}}classEgimp implements e.g { Public voidf () {}}classEIMP2 implements E { Public voidg () {}classEG implements e.g { Public voidf () {}}}  Public Static voidMain (string[] args) {A a=NewA (); //Unable to access A.D//A.D ad = a.getd (); //return only A.D//A.dimp Di2 = a.getd (); //cannot access member of interface//a.getd (). f ();A A2 =NewA ();    A2.received (a.getd ()); }}

 Interfaces can also be implemented as private, just like A.D. So what are the benefits of a private nested interface? It can be implemented as a private class or as a public class (a.dimp2). However,A.DIMP2 can only be used by itself. You can't say that it implements a private interface, D. Therefore, implementing a private interface is just one way. It can force the definition in the interface not to add any type information (that is, to not allow upward transformation).

In Main () , attempts to use getd () have failed several times. Only one way to succeed is to give the return value to the object that has permission to use it.

The interface E indicates that the interfaces can also be nested between each other. An interface nested in another interface is automatically public.

It is important to note that when implementing an interface, you do not need to implement any interfaces nested within it. Also, theprivate interface cannot be implemented outside the class that defines it.

9. Interface and Factory  

Interfaces are the way to implement multiple inheritance, and the typical way to generate objects that follow an interface is the factory method design pattern . This differs from the direct invocation, where we call the Create method on the factory object, and the factory object will generate an object of an implementation of the interface. Theoretically, in this way, our code will be completely detached from the implementation of the interface, which allows us to transparently replace one implementation with another. The structure of the factory method is shown below:

InterfaceService {voidmethod1 (); voidmethod2 ();}Interfaceservicefactory {Service getService ();}classImplementation1 implements Service { Public voidmethod1 () {System. out. println ("Implementation1 method1"); }        Public voidmethod2 () {System. out. println ("Implementation1 method2"); }}classImplementation1factory implements Servicefactory { PublicService GetService () {return NewImplementation1 (); }}classImplementation2 implements Service { Public voidmethod1 () {System. out. println ("Implementation2 method1"); }        Public voidmethod2 () {System. out. println ("Implementation2 method2"); }}classImplementation2factory implements Servicefactory { PublicService GetService () {return NewImplementation2 (); }} Public classFactories { Public Static voidServiceconsumer (servicefactory fact) {Service s=NewFact.getservice ();        S.method1 ();    S.METHOD2 (); }     Public Static voidMain (string[] args) {Serviceconsumer (Newimplementation1factory ()); Serviceconsumer (Newimplementation2factory ());}/*OutputImplementation1 method1implementation1 method2implementation2 method1implementation2 method2*/

  If it is not factory-style, the above code must somewhere specify the exact type of service to be created so that the appropriate constructor can be called.

10. Summary

Any abstraction should be the result of real demand. The appropriate principle is to prioritize classes rather than interfaces. Starting with a class, refactoring if the interface must become very explicit. Interface is a kind of tool, but it is easy to be abused.

Java Programming Ideas Learn note 9

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.