Interfaces and internal classes provide us with a more structured method to separate interfaces from implementations.
9.1 abstract classes and abstract methods
Java provides a mechanism called an abstract method. This method is declared without a method body. The statement Syntax:
abstract void f();
Classes that contain abstract methods are called abstract classes. If a class contains one or more abstract methods, the class is limited to abstract (otherwise, the compiler reports an error ).
We may also create abstract classes without abstract methods.
Abstract classes and abstract methods are very useful because they can clarify the abstraction of classes and tell users and compilers how to use them. Abstract classes are useful refactoring tools because they allow us to easily move public methods up the integration hierarchy.
9.2 Interface
Interfaces are used to establish protocols between classes.
The interface can contain fields, but these fields are implicitly static and final.
You can declare the method as public as shown in the interface, but even if you do not do this, they are also public. The method defined in the interface must be public.
9.3 completely decoupled
Policy design mode: Create a method that can have different behaviors based on the passed parameter objects.
//: interfaces/classprocessor/Apply.javapackage interfaces.classprocessor;import java.util.*;import static net.mindview.util.Print.*;class Processor { public String name() { return getClass().getSimpleName(); } Object process(Object input) { return input; }}class Upcase extends Processor { String process(Object input) { // Covariant return return ((String)input).toUpperCase(); }}class Downcase extends Processor { String process(Object input) { return ((String)input).toLowerCase(); }}class Splitter extends Processor { String process(Object input) { // The split() argument divides a String into pieces: return Arrays.toString(((String)input).split(" ")); }}public class Apply { public static void process(Processor p, Object s) { print("Using Processor " + p.name()); print(p.process(s)); } public static String s = "Disagreement with beliefs is by definition incorrect"; public static void main(String[] args) { process(new Upcase(), s); process(new Downcase(), s); process(new Splitter(), s); }} /* Output:Using Processor UpcaseDISAGREEMENT WITH BELIEFS IS BY DEFINITION INCORRECTUsing Processor Downcasedisagreement with beliefs is by definition incorrectUsing Processor Splitter[Disagreement, with, beliefs, is, by, definition, incorrect]*///:~
Adapter design mode: the code in the adapter accepts your interfaces and generates the interfaces you need.
//: interfaces/interfaceprocessor/FilterProcessor.javapackage interfaces.interfaceprocessor;import interfaces.filters.*;class FilterAdapter implements Processor { Filter filter; public FilterAdapter(Filter filter) { this.filter = filter; } public String name() { return filter.name(); } public Waveform process(Object input) { return filter.process((Waveform)input); }}public class FilterProcessor { public static void main(String[] args) { Waveform w = new Waveform(); Apply.process(new FilterAdapter(new LowPass(1.0)), w); Apply.process(new FilterAdapter(new HighPass(2.0)), w); Apply.process( new FilterAdapter(new BandPass(3.0, 4.0)), w); }} /* Output:Using Processor LowPassWaveform 0Using Processor HighPassWaveform 0Using Processor BandPassWaveform 0*///:~
9.4 multi-inheritance in Java
In the export class, there is no mandatory requirement that there must be an abstract or "concrete" (without any abstract method) base class. If you want to inherit from a non-interface class, you can only inherit from one class. All other basic elements must be interfaces. All interface names must be placed after the implements keyword and separated by commas. You can inherit any number of interfaces and convert them up to every interface, because each interface is an independent type.
Remember that the preceding example shows the core reason for using interfaces: to be able to transform upwards into multiple base types (and the resulting flexibility ). However, the second reason for using interfaces is the same as using abstract base classes: Prevent client programmers from creating objects of these classes and ensure that this is only an interface.
9.5 extend interfaces through inheritance
In general, extends can be used for a single class, but multiple base class interfaces can be referenced.
If a class inherits both a class and an interface, and both the base class and interface have the same function, there is only one same method in the export class.
If the function signature is different, the two methods can exist simultaneously. However, reload methods are inseparable only by using the return value type.
9.6 adaptation Interface
To allow methods to accept interface types is a method that allows any class to adapt to this method.
9.7 fields in the interface
The domain defined in the interface cannot be "Empty final", but can be initialized by a non-constant expression. Of course, these fields are not part of the interface, and their values are stored in the static storage area of the interface.
9.8 nested Interface
Interfaces can be nested in classes or other interfaces.
Implementing a private interface is only one way. It can force the method definition in this interface not to add any type information (that is, the upward transformation is not allowed ).
If a method returns a private interface, only one method can be successful, that is, the return value is handed over to the object with the right to use it.
An interface nested in another interface is automatically public, and cannot be declared as private.
When implementing an interface, you do not need to implement any interfaces nested inside it.
//: interfaces/nesting/NestingInterfaces.javapackage interfaces.nesting;class A { interface B { void f(); } public class BImp implements B { public void f() {} } private class BImp2 implements B { public void f() {} } public interface C { void f(); } class CImp implements C { public void f() {} } private class CImp2 implements C { public void f() {} } private interface D { void f(); } private class DImp implements D { public void f() {} } public class DImp2 implements D { public void f() {} } public D getD() { return new DImp2(); } private D dRef; public void receiveD(D d) { dRef = d; dRef.f(); }}interface E { interface G { void f(); } // Redundant "public": public interface H { void f(); } void g(); // Cannot be private within an interface: //! private interface I {}}public class NestingInterfaces { public class BImp implements A.B { public void f() {} } class CImp implements A.C { public void f() {} } // Cannot implement a private interface except // within that interface's defining class: //! class DImp implements A.D { //! public void f() {} //! } class EImp implements E { public void g() {} } class EGImp implements E.G { public void f() {} } class EImp2 implements E { public void g() {} class EG implements E.G { public void f() {} } } public static void main(String[] args) { A a = new A(); // Can't access A.D: //! A.D ad = a.getD(); // Doesn't return anything but A.D: //! A.DImp2 di2 = a.getD(); // Cannot access a member of the interface: //! a.getD().f(); // Only another A can do anything with getD(): A a2 = new A(); a2.receiveD(a.getD()); }} ///:~
9.9 interface and factory
An interface is a way to implement multi-inheritance. The classic way to generate objects that follow an interface is the factory method design mode. This is different from using the constructor directly. We call the creation method on the factory object, and the factory object will generate a specific implementation object of the interface. Theoretically, in this way, our code is completely separated from the implementation of the interface, which allows us to transparently replace an implementation with another implementation.
//: interfaces/Factories.javaimport static net.mindview.util.Print.*;interface Service { void method1(); void method2();}interface ServiceFactory { Service getService();}class Implementation1 implements Service { Implementation1() {} // Package access public void method1() {print("Implementation1 method1");} public void method2() {print("Implementation1 method2");}}class Implementation1Factory implements ServiceFactory { public Service getService() { return new Implementation1(); }}class Implementation2 implements Service { Implementation2() {} // Package access public void method1() {print("Implementation2 method1");} public void method2() {print("Implementation2 method2");}}class Implementation2Factory implements ServiceFactory { public Service getService() { return new Implementation2(); }}public class Factories { public static void serviceConsumer(ServiceFactory fact) { Service s = fact.getService(); s.method1(); s.method2(); } public static void main(String[] args) { serviceConsumer(new Implementation1Factory()); // Implementations are completely interchangeable: serviceConsumer(new Implementation2Factory()); }} /* Output:Implementation1 method1Implementation1 method2Implementation2 method1Implementation2 method2*///:~