Java interface

Sometimes you must derive a subclass from several classes and inherit all their properties and methods. However, Java does not support multiple inheritance. With an interface, you can get the effect of multiple inheritance.

Interface is the combination of abstract method and constant value definition;

In essence, an interface is a special abstract class. This abstract class only contains the definitions of constants and methods, without the implementation of variables and methods;

Implementation interface class: class subclass implements interfacea {}

A class can implement multiple interfaces, and interfaces can also inherit other interfaces;

Interface features:

Example of interface definition:

The class implementing the interface must provide the concrete implementation of all methods in the interface before instantiation, otherwise it needs to be declared as an abstract class;

The main function of the interface is to be implemented by the implemented class;

Similar to inheritance relationship: there is polymorphism between interface and implementation class;

When there is an inheritance and implementation relationship, inherit first and then implement;

There are problems when adding an abstract method to an abstract class: the parent class adds an abstract method, and the subclass must implement the abstract method, otherwise the subclass must be declared as an abstract class;

Solution: create a new interface with the abstract method in the interface and let the subclass implement it;

For example: a cook who can sing is a good teacher.

If we use abstract classes to realize: teacher inheritance cook inheritance singer inheritance person, but there is no corresponding relationship among teacher, cook and singer;

If the interface is used to realize: Teacher - successor - person, then the teacher realizes the chef interface and the teacher realizes the singer interface;

Person. java

Cooking. java

Singing. java

SCTeacher. java

Main. java

Output:

Name: Tom age: 12 gender: 1 the course taught is: the math teacher's cooking is very good, and the teacher's singing is very good

The content of this article comes from the network collection of netizens. It is used as a learning reference. The copyright belongs to the original author.
THE END
分享
二维码
< <上一篇
下一篇>>