The concept and use of Java interface <br />In an abstract class, one or more abstract methods can be included; but in an interface, all methods must be abstract and cannot have a method body. More "abstract" than abstract classes.
Interface keyword is declared, which can be regarded as a special abstract class that specifies what a class must do, rather than specifying how it does it.
There are also many examples of interfaces in reality, such as serial computer hard drives. The Serial ATA committee has designated the Serial ATA 2.0 specification, which is an interface. The Serial ATA committee is not responsible for producing hard drives, but only specifies common specifications.
Seagate, Hitachi, Samsung and other manufacturers will produce hard disks that meet the interface according to the specifications, and these hard disks can be generalized. If you are using a 160G Hitachi serial hard disk, you will be upgraded now. You can purchase a 320G Seagate serial hard disk and install it. You can continue to use it when you go up.
The following code can simulate the Serial ATA committee to define the following serial hard disk interface:
//Serial hard disk interface public interface SataHdd{ //Number of connection lines public static final int CONNECT_LINE=4; //Write data public void writeData(String data); //Read data public String rea dData();}Note: The member variables declared in the interface are all public static final by default and must be displayed initialized. Therefore, these modifiers can be omitted when declaring constants.
Interfaces are a collection of several constants and abstract methods, which currently seem to be similar to abstract classes. Indeed, interfaces evolved from abstract classes, so unless otherwise specified, interfaces enjoy the same "treatment" as classes. For example, multiple classes or interfaces can be defined in the source program, but at most one public class or interface can be available. If there is one, the source file must take the same name as the public class and interface. Like the inheritance format of a class, interfaces can also be inherited, and sub-interfaces can inherit constants and abstract methods in the parent interface and add new abstract methods, etc.
However, the interface has its own characteristics, summarized as follows.
1) Only abstract methods can be defined in the interface. These methods default to public abstract, so these modifiers can be omitted when declaring methods. Trying to define instance variables, non-abstract instance methods and static methods in an interface are all illegal. For example:
public interface SataHdd{ //The number of connection lines public int connectLine; //Compilation error, connectLine is regarded as a static constant and must be explicitly initialized //Write data protected void writeData(String data); //Compilation error , must be public Type //Read data public static String readData(){ //Compilation error, the interface cannot contain static method return "data"; //Compilation error, the interface can only contain abstract methods, }}3) There is no constructor in the interface and cannot be instantiated.
4) One interface does not implement another interface, but can inherit multiple other interfaces. The multi-inheritance feature of the interface makes up for the single inheritance of the class. For example:
//Serial hard disk interface public interface SataHdd extends A,B{ // Number of connection lines public static final int CONNECT_LINE = 4; // Write data public void writeData(String data); // Read data public c String readData(); }interface A{ public void a();}interface B{ public void b();}Why use interface
In large-scale project development, it may be necessary to insert a class from the middle of the inheritance chain to allow its subclasses to have certain functions without affecting their parent classes. For example, A -> B -> C -> D -> E, A is an ancestor class. If you need to add some common functions to C, D, and E classes, the easiest way is to let C class inherit another class. But the problem is that Java is a single inheritance language. C can no longer inherit another parent class. It can only move to the top of the inheritance chain, and let A inherit another parent class. In this way, the modifications to C, D, and E classes affect the entire inheritance chain and are not pluggable.
The interface is a guarantee of insertability. Any class in an inheritance chain can implement an interface, which will affect all subclasses of this class, but will not affect any parent class of this class. Such classes will have to implement the methods specified by this interface, and subclasses can automatically inherit these methods from this class, and at this time, these subclasses are pluggable.
What we care about is not a specific class, but whether this class implements the interface we need.
The interface provides interpolation and method calls. The larger the scale of the software system, the longer the life cycle. The interface ensures the flexibility and scalability of the software system and the interpolationability.
Interfaces play an important role in object-oriented Java programming. In fact, one of the most important tasks in the design stage is to design the interfaces of each part, and then form the basic framework structure of the program through the combination of interfaces.
Use of interfaces
The use of interfaces is somewhat different from that of classes. Where you need to use a class, the new keyword will be used directly to build an instance of a class, but the interface cannot be used like this because the interface cannot directly use the new keyword to build an instance.
An interface must implement its abstract methods through a class, and then instantiate the class. The keyword of the class implementation interface is implements.
If a class cannot implement all abstract methods of the interface, then the class must be defined as an abstract method.
An instance of an interface is not allowed to be created, but a reference variable of the interface type is allowed to be defined, which points to an instance of the class that implements the interface.
A class can only inherit one parent class, but can implement multiple interfaces.
The format of the implementation interface is as follows:
Modifier class class name extends parent class implements multiple interfaces {
Implementation method
}
Please see the following example:
import static java.lang.System.*;public class Demo{ public static void main(String[] args) { SataHdd sh1=new SeagateHdd(); //Initialize Seagate hard disk SataHdd sh2 =new SamsungHdd(); //Initialize Samsung Hard disk}}//Serial hard disk interface interface SataHdd{ //Number of connection lines public static final int CONNECT_LINE=4; //Write data public void writeData(String data); //Read data public String rea dData();}/ / Repair hard disk interface fixHdd{ // Repair address String address = "Haidian District, Beijing"; // Start repair boolean doFix();}// SeagateHdd implements SataHdd, fixHdd{ // SeagateHd drive read data p ublic String readData(){ return "data"; } //Seagate hard drive writeData(String data) { out.println("Write successful"); } // Repair Seagate hard drive public boolean doFix(){ return true; }}//Samsung hard drive class SamsungHdd implements SataHdd{ //Samsung hard drive readData(){ return "data"; } //Samsung hard drive writeData(String data){ out.println ("Write successfully"); }}//A bad-quality hard disk cannot write data abstract class XXHdd implements SataHdd{ //Hard disk reads data public String readData() { return "data"; }}Use interface as type
The interface is used as a reference type. Any instance of the class implementing the interface can be stored in variables of the interface type. Through these variables, the methods in the interface implemented in the class can be accessed. The Java runtime system will dynamically determine that it should be Which class method is used is actually calling the corresponding implementation class method.
Examples are as follows:
public class Demo{ public void test1(A a) { a.doSth(); } public static void main(String[] args) { Demo d = new Demo(); A a = new B(); d.test1( a); }}interface A { public int doSth();}class B implements A { public int doSth() { System.out.println("now in B"); return 123; }} Running results:
now in B
As you see, interfaces can be used as a type, using interfaces as methods parameters and return types.
The difference between Java interface and abstract class <br />Classes are object templates, and abstract classes and interfaces can be regarded as templates of concrete classes.
Since from a certain perspective, interfaces are a special abstract class, they have a deep connection and have great similarities, so it is easy to be confused about who to use. We first analyze the similarities they have.
They all represent abstract layers of tree-like structures. When using reference variables, try to use the abstract layer of the class structure to separate the definition and implementation of the method. This has the benefit of loosely coupled code.
None of them can be instantiated.
All can contain abstract methods. Abstract methods are used to describe what functions the system provides without having to care about specific implementations.
Let’s talk about the main differences between abstract classes and interfaces.
1) Abstract classes can provide implementations for some methods, avoiding repeated implementations of these methods in subclasses, and improving the reusability of code. This is the advantage of abstract classes; while the interface can only contain abstract methods, not any implementations. .
public abstract class A{ public abstract void method1(); public void method2(){ //A method2 }}public class B extends A{ public void method1() { //B method1 }}public class C extends A{ public void method1(){ //C method1 }}Abstract class A has two subclasses B and C. Since A has the implementation of method method2 in it, the method2 method does not need to be rewrite in subclasses B and C. We say that A provides public functions for subclasses, or A constrains it. behavior of subclasses. method2 is an example of the reusable code. A does not define the implementation of method1, that is, B and C can implement the method1 method according to their own characteristics, which reflects the characteristics of loose coupling.
Change it to the interface and see:
public interface A{ public void method1(); public void method2();}public class B implements A{ public void method1(){ //B method1 } public v oid method2(){ //B method2 }}public class C implements A{ public void method1(){ //C method1 } public void method2(){ //C method2 }}Interface A cannot provide public functions for implementing classes B and C, which means that A cannot constrain the behavior of B and C. B and C can freely exert their characteristics and realistic method1 and method2 methods, and interface A has no control ability.
2) A class can only inherit a direct parent class (maybe an abstract class), but a class can implement multiple interfaces, which is the advantage of the interface.
interface A{ public void method2();}interface B{ public void method1();}class C implements A,B{ public void method1(){ //C method1 } publ ic void method2(){ //C method2 }} //C can be used so flexibly, and C has the opportunity to expand and implement other interfaces A a=new C(); B b=new C();abstract class A{ public abstract void method1();}abstract class B extends A{ public abstract void method2();}class C extends B{ public void method1(){ //C method1 } public void method2() { //C method2 }}For Class C, there will be no chance to inherit other parent classes.
To sum up, interfaces and abstract classes have their own advantages and disadvantages. In the selection of interfaces and abstract classes, this principle must be followed:
The behavioral model should always be defined through interfaces rather than abstract classes, so interfaces are usually preferred and abstract classes should be used as few as possible.
When choosing an abstract class, it is usually the following situation: you need to define the behavior of the subclass and provide general functions for the subclass.