In depth analysis of the use of the Java interface of interface

  • 2020-04-01 04:13:30
  • OfStack

The concept and use of Java interface
In an abstract class, you can include one or more abstract methods. But in an interface, all methods must be abstract, and there must be no method body, which is more "abstract" than an abstract class.

Interfaces are declared using the interface keyword as a special kind of abstract class that specifies what a class must do, rather than how it must do it.

There are many examples of interfaces in the real world, such as Serial port computer hard drives, and the Serial ATA committee specifies the Serial ATA 2.0 specification, which is the interface. The Serial ATA committee is not responsible for the production of hard drives, it simply specifies generic specifications.

Seagate, Hitachi, samsung and other manufacturers will according to the specification of the production of the interface of the hard disk, these hard disks can be realized in general, if you are using a 160G Hitachi serial port hard disk, now to upgrade, you can buy a 320G Seagate serial port hard disk, installation can continue to use.

The following code can simulate the Serial ATA committee defining the following Serial port hard disk interfaces:


//Serial hard disk interface
public interface SataHdd{
 //Number of connecting wires
 public static final int CONNECT_LINE=4;
 //Write the data
 public void writeData(String data);
 //Read the data
 public String readData();
}

Note: the declared member variables in the interface are public static final by default and must be initialized. Therefore, these modifiers can be omitted when constant declarations are made.

An interface is a collection of constants and abstract methods that look like abstract classes at the moment. Indeed, interfaces have evolved from abstract classes, so they enjoy the same "treatment" as classes, except as specified. For example, multiple classes or interfaces can be defined in the source program, but there can be no more than one public class or interface, and if there is one, the source file must have the same name as the public class and interface. Like the inheritance format of classes, interfaces can be inherited from one another, and child interfaces can inherit constants and abstract methods from their parent interfaces and add new abstract methods.

However, interfaces have some characteristics of their own, which are summarized as follows.

1) only abstract methods can be defined in the interface. These methods are public abstract by default, so you can omit these modifiers when declaring methods. It is illegal to try to define instance variables, non-abstract instance methods, and static methods in an interface. Such as:


public interface SataHdd{
 //Number of connecting wires
 public int connectLine; //There was a compilation error and the connectLine is treated as a static constant and must be explicitly initialized
 //Write the data
 protected void writeData(String data); //Compile error, must be public type
 //Read the data
 public static String readData(){ //Compilation error, the interface cannot contain static methods
  return " data "; //Compiler error, interface can only contain abstract methods,
 }
}

3) there is no constructor in the interface and it cannot be instantiated.

4) an interface does not implement another interface, but it can inherit from many other interfaces. The multi-inheritance feature of the interface makes up for the single inheritance of the class. Such as:


//Serial hard disk interface
public interface SataHdd extends A,B{
 //Number of connecting wires
 public static final int CONNECT_LINE = 4;
 //Write the data
 public void writeData(String data);
 //Read the data
 public String readData();
}
interface A{
 public void a();
}
interface B{
 public void b();
}

Why use interfaces

In large project development, you might want to insert a class from the middle of the inheritance chain so that its subclasses have some functionality without affecting their parent classes. For example A - > B - > C - > D - > E, A is the ancestor class, if you need to add some general functionality for C, D, E, the easiest way is to let C class inherit from another class. But here's the problem: Java is A single-inheritance language, and you can't let C inherit from another parent class until you move to the top of the inheritance chain and let A inherit from another parent class. As a result, the changes to the C, D, and E classes affect the entire inheritance chain, and there is no pluggable design.

An interface is a guarantee of pluggability. Any class in an inheritance chain can implement an interface that affects all subclasses of this class, but not any parent class of this class. This class will have to implement the methods specified by the interface, and subclasses will automatically inherit the methods from this class, at which point they become pluggable.

What we care about is not the specific class, but whether the class implements the interface we need.

Interface provides intercalation and pluggability on method calls. The larger the scale of the software system, the longer the life cycle, the more flexible and extensible the interface makes the software system, and the pluggability is guaranteed.

Interfaces play an important role in object-oriented Java programming. In fact, one of the most important tasks in the design phase is to design the interface of each part, and then through the combination of interfaces, form the basic framework structure of the program.
Use of interface

The use of interfaces is somewhat different from the use of classes. Where the class is needed, an instance of the class is built directly using the new keyword, but the interface cannot be used in this way because the interface cannot build the instance directly using the new keyword.

An interface must implement its abstract method via a class, and then instantiate the class. The keyword for a class implementing an interface is implements.

If a class cannot implement all the abstract methods of the interface, the class must be defined as an abstract method.

It is not allowed to create an instance of the interface, but to define a reference variable of the interface type that points to an instance of the class that implements the interface.

A class can inherit from only one parent, but can implement multiple interfaces.

The format of the implementation interface is as follows:
Modifier class name extends superclass implements multiple interfaces {
      Implementation method
}

Here's an example:


import static java.lang.System.*;
public class Demo{
 public static void main(String[] args) {
  SataHdd sh1=new SeagateHdd(); //Initializes the Seagate hard drive
  SataHdd sh2=new SamsungHdd(); //Initialize the samsung hard drive
 }
}
//Serial hard disk interface
interface SataHdd{
 //Number of connecting wires
 public static final int CONNECT_LINE=4;
 //Write the data
 public void writeData(String data);
 //Read the data
 public String readData();
}
//Maintenance hard disk interface
interface fixHdd{
 //Maintenance address
 String address = " Haidian district, Beijing ";
 //Begin to repair
 boolean doFix();
}
//Seagate hard disk
class SeagateHdd implements SataHdd, fixHdd{
 //Seagate hard disk Read the data 
 public String readData(){
  return " data ";
 }
 //Seagate hard disk Write data 
 public void writeData(String data) {
  out.println(" Write to successful ");
 }
 //  maintenance Seagate hard disk
 public boolean doFix(){
  return true;
 }
}
//Samsung hard drive
class SamsungHdd implements SataHdd{
 //Samsung hard drive Read the data 
 public String readData(){
  return " data ";
 }
 //Samsung hard drive Write data 
 public void writeData(String data){
  out.println(" Write to successful ");
 }
}
// Some bad hard drive, no Write the data
abstract class XXHdd implements SataHdd{
 //Hard drive read data
 public String readData() {
  return " data ";
 }
}

The interface is used as a type

Interface is used as a reference type, any instance of a class to implement this interface can be stored in the interface type of variable, through these variables can be accessed in the implementation of the interface in the method, the Java runtime system can dynamically determine which class should be used in the method, is actually call the corresponding implementation class method.

Here's an example:


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;
 }
}

Operation results:


now in B

You see that the interface can be used as a type, with the interface as the argument to the method and the return type.


The difference between a Java interface and an abstract class
Classes are templates for objects, and abstract classes and interfaces can be thought of as templates for concrete classes.

Because an interface is, in some ways, a special kind of abstract class, they have deep roots and are very similar, so it's easy to get confused about who to use. Let's first analyze what they have in common.
Both represent layers of abstraction for tree-like structures. When using reference variables, try to use an abstraction layer of the class structure to separate the definition and implementation of methods, which has the benefit of loose coupling to the code.
None of them can be instantiated.
Both can contain abstract methods. Abstract methods are used to describe what the system provides, regardless of the implementation.

Here's the main difference between an abstract class and an interface.

1) abstract class can provide implementation for some methods, avoid repeating the implementation of these methods in subclasses, and improve the reusability of code, which is the advantage of abstract class; An interface can contain only abstract methods, not any implementation.


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, and since A has an implementation of the method method2, and subclasses B and C don't have to override the method2 method, let's say that A provides A common method for subclasses, or that A constrains their behavior. Method2 is an example of code reuse. A does not define an implementation of method1, which means that B and C can implement method1 methods according to their own characteristics, which again reflects the property of loose coupling.

Replace it with an interface:


public interface A{
 public void method1();
 public void method2();
}
public class B implements A{
 public void method1(){
  //B method1
 }
 public void method2(){
  //B method2
 }
}
public class C implements A{
 public void method1(){
  //C method1
 }
 public void method2(){
  //C method2
 }
}

Interface A cannot provide common functions for implementing classes B and C, that is to say, A cannot constrain the behavior of B and C. So B and C are free to play their own game and the reality is that method1 and method2 methods, interface A has no control.

2) a class can only inherit from one direct parent class (possibly 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
 }
 public void method2(){
  //C method2
 }
}
//You can use C so flexibly, and C has the opportunity to extend 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 from other parent classes.

To sum up, interfaces and abstract classes have their own advantages and disadvantages. In the choice of interfaces and abstract classes, the following principle must be followed:
The behavior model should always be defined through an interface rather than an abstract class, so it is often a matter of prioritizing the interface and minimizing the use of abstract classes.
When choosing an abstract class, you typically want to define the behavior of the subclass and provide it with generic functionality.


Related articles: