The last article was about the role of final keyword in Java and Java Abstract Class. First of all, I would like to apologize to you. I planned to update Java interface and the relationship between Java classes in this article, but I know a little more about Java interface. So today first update “Java interface”, another knowledge point, we fill up behind, understanding ha.

Let’s share:

Java interfaces

Java Interface Overview

The computer can connect different peripherals through these interfaces and expand the function of the computer. When the computer realizes an interface, it has the function of connecting the interface device. If the interface is not realized, it does not have the function.

There are USB slots in the computer, whether it is keyboard/mouse/hard drive/printer, as long as there is a USB plug to connect to the computer, these devices are made by different manufacturers, they all follow the USB protocol.

Interfaces in Java programs are used to extend the functions of classes. Interfaces can be understood as the encapsulation of functions, and interfaces in Java can also be understood as an operation specification (protocol).

Java interface definition and implementation

1.Java interface definition syntax:

[modifiers] interface Interface name {

Methods in interfaces use the public Abstract modifier by default

By default, fields in an interface use the public static final modifier

An interface can define a public static static method

Define the public Default method

}

2. Use of Java interfaces

[modifiers] class class name implements interface {

Abstract methods that need to be overridden for the interface

package com.wkcto.chapter01.interfaces.demo01; Void fly(); /** * void fly(); }Copy the code
package com.wkcto.chapter01.interfaces.demo01; ** @author ** / public class Bird implements Flyable {@override public void fly() { System.out.println(" Birds fly in the sky "); }}Copy the code

Practice: Define the interface to encapsulate the swimming function, fish can swim, dogs can swim, people can swim.

Java interface polymorphism

package com.wkcto.chapter01.interfaces.demo01; /** * 1) An interface is a reference data type. It can define variables, but the interface cannot instantiate objects. * * @author * */ public class Test {public static void main(String[]); Args) {//1) Interface definition variable Flyable Flyable; //2) The interface cannot instantiate the object // flyable = new flyable (); //Cannot instantiate the type Flyable //3) Interface references can be assigned to the implementation object Flyable = new Bird(); flyable.fly(); flyable = new Plane(); flyable.fly(); }}Copy the code
package com.wkcto.chapter01.interfaces.demo01; @author ** / public class Test02 {public static void main(String[] args) {// Create a Slingshot object slingshot = new Slingshot(); // Create Bird object Bird = new Bird(); slingshot.shoot(bird); Plane Plane = new Plane(); slingshot.shoot(plane); }}Copy the code
package com.wkcto.chapter01.interfaces.demo01; /** * The slingshot class can eject any flightable object ** Always, take the interface reference as the method parameter, * @author * */ public class Slingshot {// Any object that can fly can be ejected, Public void shoot(Flyable Flyable) {// The object is Flyable. Fly (); }}Copy the code

Practice: The natatorium only accepts animals that can swim.

Java Interface Description

1. When a class implements an interface, it needs to rewrite the abstract method in the interface to have the function defined in the interface; If a class implements an interface and does not override all the abstract methods in the interface, the class needs to be defined as abstract.

2. A class that implements multiple interfaces, separated by commas, needs to override all abstract methods in all interfaces.

3. Interfaces can also inherit and support multiple inheritance. You can extend the functions of interfaces in subinterfaces.

In JDK8, there are only four parts: public abstract default method, public static final default field, public static static method, public default method.

Similarities and differences between Java abstract classes and interfaces

The same

1. Can define abstract methods

2. The object cannot be instantiated

3. The abstract methods of the interface/abstract class all need to be overridden

4. You can define public static final fields and public static methods in any interface or abstract class

The difference between

1. Different meanings

An abstract class abstracts a class at a higher level

Interfaces encapsulate functionality

2. Different definitions

Abstract classes are defined using abstract class

Interfaces are defined using interfaces

3. Different content

Abstract class in addition to the definition of abstract methods, can also define instance variables/instance methods/static variables/static methods, constructors and other ordinary class members.

In addition to abstract methods, the interface can also define public static final fields,public static methods,public default methods.

Abstract classes have constructors, interfaces have no constructors; You can use the default modifier on an interface, but not on an abstract class.

4. Different ways of use

Abstract classes typically exist as parent classes that require subclasses to inherit through extends.

The interface needs to be implemented through the class implements.

5. Inheritance

Classes support only single inheritance and interfaces support multiple inheritance

6. Different application scenarios

If only to extend the functionality of the class, the interface is preferred.

If you need to save different data in addition to the function, choose an abstract class, and the abstract method in the abstract class needs to be overridden in the subclass, and the abstract class can constrain all the subclasses to have a certain function.

Java interface application

1. Interfaces encapsulate functions

If the fly() function is encapsulated in the Flyable interface, the fly() method needs to be overridden to extend the functionality of the class that implements the Flyable interface.

The Comparable interface, such as the system-defined Comparable interface, encapsulates the ability to compare two objects, and can be implemented if a class wants to compare the size of two objects.

package com.wkcto.chapter01.interfaces.demo03; /** * Define the Person class. * If you want the object of the Person class to have the ability to compare sizes, We can accomplish this by implementing the Comparable interface. The <T> following the Comparable interface is a generic, which takes the data type as an argument. The generic following Comparable specifies the data type of the comparison object class Person implements Comparable<Person> { String name; int age; int height; /** * Overrides the abstract method of the interface, specifying the comparison rule * returns positive if the current object is larger than the parameter o, negative if the current object is smaller than the parameter o, Override public int compareTo(Person o) {return this.age - o.age; } public Person(String name, int age, int height) { super(); this.name = name; this.age = age; this.height = height; }}Copy the code

2. An interface can be understood as a set of operating specifications (a protocol)

Baidu News contains modules such as home page/sports/games/women/cars, no matter which module can add news, delete news, modify news, query news. These functions can be defined in an interface that different modules implement to unify their operations.

Advocate interface oriented programming

1. The use of interfaces is flexible. A class can implement multiple interfaces while inheriting from its parent class

Describe the part-time students, part-time students have both the characteristics of students, and the characteristics of workers, if the class is allowed to inherit, can directly let the part-time students inherit students and workers at the same time.

Java does not allow multiple inheritance, can let the working students inherit the student class, the working operation defined as the interface, the working students implement the working interface.

It describes the working students, to some extent, can also solve the problem of multiple inheritance of classes

package com.wkcto.chapter01.interfaces.demo04; @author ** / public class Student {String name; public void study() { System.out.println } }Copy the code
package com.wkcto.chapter01.interfaces.demo04; Public interface workshop {void work(); }Copy the code
package com.wkcto.chapter01.interfaces.demo04; Public class PartTimeStudent implements Student in a workshop Public void work() {system.out.println} @override public void work() {system.out.println} @override public void work() { System.out.println } }Copy the code

Exercise 1

1. Describe a pencil with an eraser. A pencil is a kind of pen with the function of erasing.

2. The interface is easy to expand, and the code can be pluggable

A reference to an interface is often taken as a parameter to a method, and various implementation-class objects can be passed when a method is called

Slingshots can shoot flying objects, and swimming pools only accept animals that can swim

3. Interfaces can layer projects

A computer can implement many different interfaces, the interface is relatively flexible

Computer USB slot, as long as there is a USB plug of the device can be connected to the computer, the interface is easy to expand

Computers are made by Lenovo /Dell/ Asus, and USB devices are made by many different manufacturers, which makes the project layered

In the model above, the project is simply divided into two layers through interfaces. One team is responsible for developing the business logic, and another team is responsible for developing the operation and optimization of the database. The requirements for developers are reduced. When the database changes, the developer of the database only needs to define a special class that operates on the database; the business logic code does not need to change.

package com.wkcto.chapter01.interfaces.demo05; @author ** / public interface DaoService {void add(); @author ** / public interface DaoService {void add(); // Add data to the database void delete(); // Delete data void update(); // Modify the data void list(); // Display all data}Copy the code
package com.wkcto.chapter01.interfaces.demo05; @author ** / public class LogicModel1 {DaoService dao; Public void addData() {system.out.println (" business logic module 1 needs to addData to the database "); dao.add(); } // deleteData public void deleteData() {system.out.println (" business logic module 1 needs to deleteData from database "); dao.delete(); Public void updateData() {system.out.println (" service logic module 1 needs to modify data in the database "); dao.update(); Public void listAllData() {system.out.println (" business logic module 1 needs to display all data from the database "); dao.list(); }}Copy the code
package com.wkcto.chapter01.interfaces.demo05; /** * define a class that operates on the MySQL database, @author * */ public class MySqlDaoImpl implements DaoService {@override public void add() {@override public void add() { System.out.println(" add data to MySQL database "); } @override public void delete() {system.out.println (" delete from MySQL database "); } @override public void update() {system.out.println (); } @override public void list() {system.out.println (); }}Copy the code
package com.wkcto.chapter01.interfaces.demo05; Public class Test {public static void main(String[] args) {LogicModel1 model1 = new  LogicModel1(); // model1.dao = new MySqlDaoImpl(); Model1.dao = new OracleDaoImpl(); model1.addData(); model1.updateData(); model1.deleteData(); model1.listAllData(); }}Copy the code

Ex 2

Simulation All animals can use their own way of communication to communicate, people speak human, dogs speak dog.

package com.wkcto.chapter01.interfaces.demo06; /** * public Speakable {void Speakable (); Talk / /}Copy the code
package com.wkcto.chapter01.interfaces.demo06; @author ** / public class implements Speakable {@override public void Speakable () { System.out.println(" woof woof ~~~~"); }}Copy the code
package com.wkcto.chapter01.interfaces.demo06; /** ** Define Animal class * each Animal has its own way of speaking ** Animal can use its own way of speaking to communicate * @author ** / public class Animal {Speakable Speakable; Public Animal(Speakable, Speakable) {super(); this.speakable = speakable; Public void talk() {speakable.speak(); }}Copy the code
package com.wkcto.chapter01.interfaces.demo06; /** * public class Dog extends Animal {public Dog(Speakable Speakable) {super(Speakable); }}Copy the code
package com.wkcto.chapter01.interfaces.demo06; * @author ** / public class Test {public static void main(String[] args) {WangWang wangWang = new WangWang(); // Dog dahuang = new Dog(wangWang); // When creating a puppy object, you need to specify its speech mode dahuang.talk(); MiaoMiao miaoMiao = new MiaoMiao(); Cat mimi = new Cat(miaoMiao); mimi.talk(); }}Copy the code

Above is the Java Interface. Java classes and relationships between classes.

Also welcome everybody exchange discussion, if this article has incorrect place, hope everybody many forgive.

Your support is my biggest motivation, if you help out, give me a thumbs up