Learning content:
Chapter 9 interface of Thinking in java
Learning suggestions: this book is more suitable for beginners who have some basic knowledge of java, and can understand all aspects of the basic knowledge of java, so as to understand this book more easily. Therefore, this book is more suitable for consolidating learning. If you want to achieve the effect of zero foundation introduction, I personally suggest that java core foundation is more suitable than this book.
Interface
Interfaces and inner classes provide us with a more structured way to separate interfaces from implementations.
1. Abstract classes and methods
If a class contains one or more abstract methods, the class must be qualified as abstract. Being an abstract class doesn't require all methods to be abstract, just declaring some methods to be abstract.
2. interface
The interface keyword produces a completely abstract class that doesn't provide any concrete implementation at all. It allows the creator to determine the method name, parameter list and return type, but there is no method body, and the interface only provides the form without any specific implementation.
To create an interface, you need to replace the class keyword with the interface keyword. Just like a class, you can add the public keyword before the interface keyword (but only if the interface is defined in a file with the same name). If you do not add the public keyword, it only has package access rights, so it can only be available in the same package, and the interface can also contain domains, but these domains are implicitly static and final.
To make a class follow a specific interface (or a set of interfaces), you need to use the implements keyword, which means: interface is just its appearance, but now I want to declare that it works. In addition, it looks like inheritance.
You can choose to explicitly declare methods as public in the interface, but even if you don't, they are public. Therefore, when implementing an interface, the methods defined in the interface must be defined as public.
3. Complete decoupling
As long as a method operates on a class rather than an interface, you can only use this class and its subclasses. If you want to apply this method to a class that is not in this inheritance structure, the interface can largely relax this limitation.
4. Multiple inheritance in Java
(1) The core reason for using interfaces: the flexibility of being able to transition up to multiple base types. The second reason: as with abstract base classes, prevents client programmers from creating objects of that class, and ensures that this is only an interface.
(2) Choice of abstract class and interface: if you want to create a base class without any method definitions and member variables, you should choose interface instead of abstract class.
interface CanSwim { void swim(); } interface CanFly { void fly(); } interface CanFight { void fight(); } class ActionCharacter { public void fight(){}; } //The parent class has implemented fit() public class Hero extends ActionCharacter implements CanFly , CanFight ,CanSwim{ @Override public void swim() { // TODO Auto-generated method stub } @Override public void fly() { // TODO Auto-generated method stub } } public class MainJava { public static void t(CanFight x){ x.fight(); } public static void u(CanSwim x){ x.swim(); } public static void v(CanFly x){ x.fly(); } public static void w(ActionCharacter x){ x.fight(); } public static void main(String[] args) { Hero h = new Hero(); //When a Hero object is created, it can be passed to any of these methods. Upward transformation t(h); u(h); v(h); w(h); } }
5. Extend the interface by inheritance
It is easy to add a new method declaration in the interface through inheritance, or to combine several interfaces in the new interface through inheritance. In both cases, a new interface can be obtained.
interface Monster { void menace(); } interface DangerousMonster extends Monster{ void destory(); } interface Lethal { void kill(); } public class DragonZilla implements DangerousMonster{ @Override public void menace() { // TODO Auto-generated method stub } @Override public void destory() { // TODO Auto-generated method stub } } //Only interface inheritance can inherit multiple interfaces interface Vampire extends DangerousMonster ,Lethal{ void drinkBlood(); } public class MainJava { static void u(Monster b){ b.menace(); } public static void main(String[] args) { //Receive instance with interface DangerousMonster barney = new DragonZilla(); u(barney); } }
6. Adapter
One of the most attractive reasons for an interface is to allow multiple concrete implementations of the same interface. In a simple case, its embodiment is usually a method that accepts the interface type, and the implementation of the interface and the objects passed to the method depend on the user of the method. Therefore, a common use of the interface is the strategy design pattern mentioned above. At this time, you write a method to perform certain operations, and the method will accept an interface specified by you. You mainly want to declare that you can call my method with any object you want, as long as your object follows my interface, which makes your method more flexible Universal and more reusable.
7. Domain in the interface
Because any domain you put into the interface is static and final automatically, the interface becomes a very convenient tool for creating constant groups.
//Any field is automatically static and final, in uppercase style public interface RandVals { Random RAND = new Random(47); int RANDOM_INT = RAND.nextInt(10); } public class MainJava { public static void main(String[] args) { //These fields are not part of the interface, and their values are stored in the static storage area of the interface print(RandVals.RANDOM_INT) ; } }
8. Nested interface
Interfaces can be nested in classes or other interfaces.
class A { interface B{ void f(); } public class BImp implements B{ public void f(){ } } public 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(); } public interface H{ void f(); } void g(); } public class MainJava { public class BImp implements A.B{ public void f(){ } } class CImp implements A.C { 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(); //a.getD() can't access A.D A a2 = new A(); a2.receiveD(a.getD()); } }
9. Interface and factory
Interface is the way to realize multiple inheritance, and the typical way to generate objects following an interface is factory method design pattern. We call the Create method on a factory object that will generate an implemented object of the interface. In theory, in this way our code is completely separate from the implementation of the interface, which allows us to transparently replace one implementation with another.
//Interface: interface abstraction of concrete class interface Service { void method1(); void method2(); } //Interface: factory class interface abstraction interface ServiceFactory { Service getServoce(); } //Base class: the base class of a concrete class public class Implementation1 implements Service{ Implementation1(){ }; public void method1() { } public void method2() { } } public class Implementation2 implements Service{ Implementation2() { } public void method1() { } public void method2() { } } //Base class: factory base class public class ImplementationFactory implements ServiceFactory{ public Service getServoce() { return new Implementation1(); } } public class Implementation2Factory implements ServiceFactory{ @Override public Service getServoce() { // TODO Auto-generated method stub return new Implementation2(); } } public class MainJava { public static void serviceConsumer(ServiceFactory fact){ //Generating objects from factory classes Service s = fact.getServoce(); s.method1(); s.method2(); } public static void main(String[] args) { serviceConsumer(new ImplementationFactory()); serviceConsumer(new Implementation2Factory()); } }
If you are not using factory methods, your code must specify the exact type of Service to be created somewhere in order to call the appropriate constructor.