The concept and use of Java Interface (interface)
In an abstract class, you can include one or more abstract methods, but in an interface (interface), all methods must be abstract and cannot have a method body, which is more "abstract" than an abstract class.
Interfaces are declared using the interface keyword, and can be viewed as a special abstract class that specifies what a class must do, rather than how it is made.
There are also many examples of interfaces in reality, such as serial computer hard drives, and the Serial ATA Commission specifies the Serial ATA 2.0 specification, which is the interface. Serial ATA Commission is not responsible for the production of hard disks, just specifying generic specifications.
Seagate, Hitachi, Samsung and other manufacturers will be in accordance with the specifications of the production of the interface of the hard disk, these hard drives can be generalized, if you are using a 160G Hitachi serial hard disk, now to upgrade, you can buy a 320G of Seagate serial hard disk, installed up can continue to use.
The following code can simulate the Serial ATA Committee to define the following serial port hard disk interfaces:
Serial hard disk Interface public
interface satahdd{
//Connection line number 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 default to public static final, and must be displayed for initialization. As a result, these modifiers can be omitted from the constant declaration.
An interface is a collection of constants and abstract methods that now appear to be similar to abstract classes. Indeed, interfaces are evolved from abstract classes, so the interface enjoys the same "treatment" as the class, in addition to special provisions. For example, a source program can define more than one class or interface, but only a class or interface that is public, and if so, the source file must have the same name as the public class and the interface. As with the inheritance format of the class, interfaces can be inherited, and sub-interfaces can inherit constants and abstract methods from the parent interface and add new abstract methods.
But the interface has some of its own characteristics, summed up as follows.
1 interface can only define abstract methods, which are public abstract by default, and can be omitted when declaring a method. It is illegal to attempt to define instance variables, non-abstract instance methods, and static methods in an interface. For example:
The number of public interface satahdd{
//Connectors public
int connectline;//Compilation error, Connectline is considered static constant, must explicitly initialize
/write Data
protected void WriteData (String data); Compilation error, must be public type
/Read data public
static String ReadData () {//Compilation error, interface cannot contain static method return
"data";//Compile error, The interface can contain only abstract methods,
}
3 There is no construction method in the interface and cannot be instantiated.
4 An interface does not implement another interface, but can inherit multiple other interfaces. The multiple inheritance features of the interface make up the single inheritance of the class. For example:
Serial hard disk Interface public
interface SATAHDD extends a,b{
//Connection line number 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 an interface
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 class. For example, a-> B-> C-> D-> E,a is an ancestor class, and if you need to add some common functionality to the C, D, and E classes, the easiest way is to have the C class inherit another class. But the problem is, Java is a single inherited language, you can no longer let C inherit another parent class, only to move to the top of the inheritance chain, let a to inherit a parent class. As a result, modifications to the C, D, and E categories affect the entire inheritance chain and do not have a pluggable design.
Interfaces are guaranteed to be pluggable. Any class in an inheritance chain can implement an interface that affects all subclasses of the class, but does not affect any of the parent classes of the class. This class will have to implement the methods specified by this interface, and subclasses can inherit these methods automatically from this class, at which point the subclasses are pluggable.
What we care about is not the specific class, but whether the class implements the interface we need.
Interface provides the association and the pluggable nature of the method invocation, the larger the software system, the longer the lifecycle, the interface makes the software system flexible and scalable, and the pluggable aspect is ensured.
Interface plays 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 form the basic frame structure of the program through the combination of interfaces.
Use of Interfaces
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 because the interface cannot use the new keyword directly to build the instance.
An interface must implement (implements) its abstract methods through a class, and then instantiate the class. The key word for the class implementation interface is implements.
If a class cannot implement all of the abstract methods of the interface, then the class must be defined as an abstract method.
Creating an instance of an interface is not allowed, but allows you to define a reference variable of an interface type that points to an instance of the class that implements the interface.
A class can inherit only one parent class, but it may implement multiple interfaces.
The format of the implementation interface is as follows:
Modifier class class name extends parent class implements multiple interfaces {
Implementation methods
}
Take a look at 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 S AMSUNGHDD ();
Initialize Samsung hard Drive}//serial hard Disk Interface interface satahdd{//connector number public static final int connect_line=4;
Write Data public void WriteData (String data);
Read Data public String readdata ();
//Repair HDD Interface interface fixhdd{//repair address String adress = "Haidian District, Beijing";
Start maintenance of the Boolean dofix ();
//Seagate Hard Disk class SEAGATEHDD implements SATAHDD, fixhdd{/Seagate hard Drive Read Data public String ReadData () {return "data";
//Seagate Hard Drive writes data public void WriteData (String data) {out.println ("write succeeded");
//repair Seagate Hard Drive public boolean dofix () {return true;
}///Samsung Hard disk class SAMSUNGHDD implements satahdd{//Samsung hard drive read Data public String ReadData () {return "data";
//Samsung hard drive writes data public void WriteData (String data) {out.println ("write succeeded");
}//An inferior hard drive, cannot write data abstract class XXHDD implements satahdd{//hard disk read data public String ReadData () {return "data";
}
}
Interface is used as a type
Interface is used as a reference type, and any instance of the class that implements the interface can be stored in a variable of that interface type. These variables allow you to access methods in the interfaces that are implemented in the class, and the Java runtime system dynamically determines which method in which class should be used, and in fact, the method that invokes the corresponding implementation class.
Examples are as follows:
public class demo{public
void Test1 (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
}
}
Run Result:
We see that interfaces can be used as a type, using interfaces as parameters and return types of methods.
the difference between Java interfaces and abstract classes
Classes are templates for objects, and abstract classes and interfaces can be seen as templates for specific classes.
Since interfaces are a special kind of abstract class in some way, they have a very strong source of similarity, so it's easy to get confused about who you choose to use. We first analyze the similarities that they have.
Represents the abstract layer of a class tree structure. When using reference variables, use the abstraction layer of the class structure as much as possible, separating the definition and implementation of the method, which has the benefit of loosely coupled code.
Can not be instantiated.
Can contain abstract methods. Abstract methods are used to describe what functions the system provides without having to be concerned with specific implementations.
Here are the main differences between abstract classes and interfaces.
1 abstract classes can provide implementations for some methods, avoid repeating them in subclasses, and improve the reusability of code, which is an advantage of abstract classes, and interfaces can contain only abstract methods and cannot contain 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
}
}
Abstract Class A has two subclasses B, C, because a has a method METHOD2 implementation, subclass B, C does not need to rewrite the Method2 method, we say that a provides a common function for subclasses, or a constrains the behavior of subclasses. METHOD2 is an example of how code can be reused. A does not define the implementation of METHOD1, which means B, C can implement METHOD1 methods according to their own characteristics, which also embodies the characteristics of loose coupling.
Then switch to 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 common functionality for implementing Class B and C, meaning that a cannot constrain the behavior of B and C. B, c free to play their own characteristics of the reality method1 and Method2 methods, interface A has no control.
2 A class can only inherit a direct parent class (possibly an abstract class), but a class may 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< c12/>}
//Can be so flexible to use C, and C also has the opportunity to extend, implement other interface
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 of inheriting other parent classes.
To sum up, interfaces and abstract classes have their pros and cons, and the choice of interfaces and abstract classes must conform to the principle that:
The behavioral model should always be defined through interfaces rather than abstract classes, so it is often preferable to use an interface as much as possible with abstract classes.
When you select an abstract class, it is usually the case that you need to define the behavior of subclasses and provide common functionality for subclasses.