An interface is used to mark a class. Different classes belong to different interfaces (through upward transformation). It is much easier to manage interfaces than to manage various classes, interfaces reflect abstract ideas. What is abstraction? Abstraction is the part of the image ".
Use interfaces to solve problems
Problem: now we need to write a database Connection class for users to use. There are two functions: one returns the Connection object and the other closes the database and closes (). The general solution is: write a class for each database, and then decide to use a specific class based on the database used by the user.
Okay. Let's take a look at the following:
(1). First, each class must have repeated code, resulting in code expansion;
(2). The most important thing is that we don't know what database the user is using. It may be Oracle, mysql, or sqlserver. This problem is very difficult to solve.
Solution:
First, we define the interface:
Public interface DataBase
{
Java. SQL. Connection openDB (String url, String user, String password );
Void close ();
}
We have defined two methods. openDB returns the Connection object and closes () to close the database;
The specific implementation is in the class that implements the DataBase interface;
Let's take a look at the implementation:
Import java. SQL .*;
Public class Mysql implements DataBase
{
Private String url = "jdbc: mysql: localhost: 3306/test ";
Private String user = "root ";
Private String password = "";
Private Connection conn;
Public Connection openDB (url, user, password)
{
// Database connection code
}
Public void close ()
{
// Close the database
}
}
Mysql class implements the DataBase interface, and the oraclesql class that implements the DataBase interface is also below;
These classes are all attributed to the DataBase interface. How can they be used in applications?
We need to define the DataBase object myDB and use myDB to manipulate the DataBase. Do not tell which class it is.
Another problem: we are not allowed to instantiate interfaces in Java, such as DataBase myDB = new DataBase ();
We can only use myDB = new Mysql () or myDB = new Oracle (). In this way, we must specify the object to be instantiated, as if the previous efforts were in vain !! What should we do? We need a factory:
Public class DBFactory
{
Public static DataBase Connection getConn ()
{
Return (new Mysql ());
}
}
The instantiated code becomes: myDB = DBFactory. getConn ();
During the whole process, the interface is not responsible for any specific operations. If other programs want to connect to the database, they only need to construct a DB object and then OK, regardless of how the factory class changes. This is the meaning of the interface ---- Abstraction