Home>

The concept and use of java interface

In the abstract class,Can contain one or more abstract methods;But in the interface, all methods must be abstract,No method body,It is more "abstract" than abstract classes.

Interfaces are declared using the interface keyword,Can be seen as a special abstract class,You can specify what a class must do,Rather than prescribe how it does it.

There are many instances of interfaces in reality,For example, serial computer hard drive,The serial ata committee specifies the serial ata 2.0 specification, which is the interface.The serial ata committee is not responsible for producing hard drives,Just specify the general specifications.

Manufacturers such as Seagate, Hitachi, and Samsung will produce hard drives that comply with the interface in accordance with specificationsThese hard disks can be universalized,If you are using a 160g Hitachi serial hard drive,It ’s time to upgrade.Can buy a 320g Seagate serial hard drive,You can continue to use it after installation.

The following code can simulate the serial ATA committee to define the following serial hard disk interfaces:

//Serial hard disk interface
public interface satahdd {
 //Number of connecting lines
 public static final int connect_line=4;
 //Write data
 public void writedata (string data);
 //Read data
 public string readdata ();
}

Note:The member variables declared in the interface are public static final by default and must be explicitly initialized.These modifiers can therefore be omitted in constant declarations.

An interface is a collection of constants and abstract methods.It currently looks similar to abstract classes.It does,Interfaces have evolved from abstract classes.Unless otherwise specified,Interfaces enjoy the same "treatment" as classes. For example, multiple classes or interfaces can be defined in the source program.But there can be at most one public class or interface,If so, the source file must have the same name as the public class and interface.Like the class inheritance format,Interfaces can also inherit,A child interface can inherit constants and abstract methods from the parent interface and add new abstract methods.

But the interface has some characteristics of its own,They 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.Try to define instance variables, non-abstract instance methods and static methods in the interface,Are illegal.E.g:

public interface satahdd {
 //Number of connecting lines
 public int connectline;//Compile error,connectline is considered a static constant,Must be explicitly initialized
 //Write data
 protected void writedata (string data);//Compile error,Must be public
 //Read data
 public static string readdata () {//Compile error,Interface cannot contain static methods
  return "data";//Compile error,The interface can only contain abstract methods, }
}

3) There is no constructor in the interface,Cannot be instantiated.

4) One interface does not implement another interface,However, multiple other interfaces can be inherited.The multiple inheritance feature of the interface makes up for the single inheritance of the class.E.g:

//Serial hard disk interface
public interface satahdd extends a, b {
 //number of connections
 public static final int connect_line=4;
 //write data
 public void writedata (string data);
 //read data
 public string readdata ();
}
interface a {
 public void a ();
}
interface b {
 public void b ();
}

Why use interfaces

In the development of large projects,May need to insert a class from the middle of the inheritance chain,Make its subclasses have some functionality without affecting their parent classes.For example a->b->c->d->e, a is an ancestor,If you need to add some common functions for c, d, eThe easiest way is to let class c inherit another class.But the problem came,java is a single inheritance language,Can't let c inherit another parent class,Only to move to the top of the inheritance chain,Let a inherit one more parent class.Thus,Modifications to classes c, d, e,Affects the entire inheritance chain,Design without insertability.

The interface is a guarantee of pluggability.Any class in an inheritance chain can implement an interface,This interface affects all subclasses of this class,It does not affect any parent classes of this class.This class will have to implement the methods specified by this interface,And subclasses can automatically inherit these methods from this class,At this point, these subclasses are pluggable.

We don't care which specific class,It's whether this class implements the interface we need.

Interfaces provide associations and pluggability on method calls,The larger the size of the software system,The longer the life cycle,Interfaces make software systems flexible and extensible,Guaranteed insertability.

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.Then through the combination of interfaces,Form the basic framework of the program.

Use of interfaces

The use of interfaces is somewhat different from the use of classes.Where classes are needed,Will use the new keyword directly to build an instance of the class,But the interface cannot be used like this,Because interfaces cannot use the new keyword directly to build instances.

An interface must implement its abstract methods through classes.Then instantiate the class.The keyword of a class implementing an interface is implements.

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

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

A class can only inherit one parent class,However, multiple interfaces can be implemented.

The format of the implementation interface is as follows:

Modifier class class name extends parent class implements multiple interfaces {

Implementation

}

Consider the following example:

import static java.lang.system. *;
public class demo {
 public static void main (string [] args) {
  satahdd sh1=new seagatehdd ();//initialize Seagate hard drive
  satahdd sh2=new samsunghdd ();//Initialize Samsung hard disk
 }
}
//Serial hard disk interface
interface satahdd {
 //Number of connecting lines
 public static final int connect_line=4;
 //Write data
 public void writedata (string data);
 //Read data
 public string readdata ();
}
//Repair hard drive interface
interface fixhdd {
 //repair address
 string address="Beijing Haidian District";
 //start repair
 boolean dofix ();
}
//Seagate hard drive
class seagatehdd implements satahdd, fixhdd {
 //Seagate hard drive reads data
 public string readdata () {
  return "data";
 }
 //Seagate hard disk write data
 public void writedata (string data) {
  out.println ("Write successfully");
 }
 //Repair Seagate hard drive
 public boolean dofix () {
  return true;
 }
}
//Samsung hard drive
class samsunghdd implements satahdd {
 //Samsung hard drive reads data
 public string readdata () {
  return "data";
 }
 //Samsung hard disk write data
 public void writedata (string data) {
  out.println ("Write successfully");
 }
}
//A poor quality hard disk,Cannot write data
abstract class xxhdd implements satahdd {
 //Hard disk read data
 public string readdata () {
  return "data";
 }
}

Interface as a type

Interfaces are used as reference types,Instances of any class that implements the interface can be stored in variables of the interface type,These variables allow access to the methods in the interface implemented in the class,The java runtime system dynamically determines which method in the class should be used,It is actually calling the method of the corresponding implementation class.

Examples are:

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 result:

now in b

You see that the interface can be used as a type,Take interfaces as method parameters and return types.

Difference between java interface and abstract class

Classes are templates for objects,Abstract classes and interfaces can be thought of as templates for concrete classes.

Because from a certain perspective,An interface is a special abstract class.They have deep roots,There are great similarities,So it's easy to get confused about who to choose.We first analyze what they have in common.

Both represent abstract layers of a tree-like structure.When using reference variables,Try to use abstract layers of class structure,Separate the definition and implementation of the method,This has the benefit of loosely coupling the code.

None can be instantiated.

Can contain abstract methods.Abstract methods are used to describe what functions the system provides,You don't have to care about the specific implementation.

Let's talk about the main differences between abstract classes and interfaces.

1) Abstract classes can provide implementations for some methods,Avoid reimplementing these methods in subclasses,Improved code reusability,This is the advantage of abstract classes;The interface can only contain abstract methods,Cannot contain 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
 }
}

The abstract class a has two subclasses b and c. Since there is an implementation of method method2 in a, subclass b and c do not need to override the method2 method.Or a restricts the behavior of the subclass.method2 is an example of code reuse.a does not define the implementation of method1, that is to say, b and c can implement the method1 method according to their own characteristics, which in turn reflects the characteristics of loose coupling.

Replace it with an interface to see:

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 public functions for implementing classes b and c.In other words, a cannot constrain the behavior of b and c. b and c can freely use their own characteristics to implement method1 and method2, and interface a has no control ability.

2) A class can only inherit a direct parent class (may be an abstract class), but a class can implement multiple interfaces,This 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 expand,Implementing 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.

In summary,There are advantages and disadvantages to interfaces and abstract classes.In the choice of interfaces and abstract classes,One must adhere to such a principle:

The behavior model should always be defined through interfaces rather than abstract classes,So usually the interface is preferred,Minimize the use of abstract classes.

When selecting an abstract class, it is usually as follows:the behavior of the subclass needs to be definedAlso provide common functionality for subclasses.

  • Previous jQuery + Ajax + PHP + Mysql implementation of paging display data example
  • Next Explain Java generics in detail