JAVA interface, java interface instance
Interface: in JAVA programming language, it is an abstract type and a set of abstract methods. interfaces are usually declared using interfaces. A class inherits the abstract methods of interfaces by inheriting interfaces.
Interfaces are not classes. interfaces are similar to classes, but they belong to different concepts. Class describes the attributes and methods of an object. The Interface contains the methods to be implemented by the class.
Unless the class implementing the interface is an abstract class, the class must define all methods in the interface.
The interface cannot be instantiated, but can be implemented. A class that implements an interface must implement all the methods described in the interface; otherwise, it must be declared as an abstract class. In addition, in Java, the interface type can be used to declare a variable. They can be a null pointer or bound to an object implemented using this interface.
Similarities between interfaces and classes:
Differences between interfaces and classes:
Interfaces have the following features:
- The interface is implicitly abstract. When an interface is declared, you do not need to useAbstractKeyword.
- Each method in the interface is also implicitly abstract and is not required for declaration.AbstractKey.
- All methods in the interface are public.
/* File name: interfaceAnimal. java */interface interfaceAnimal {public void eat (); public void travel ();}/* file name: interfaceAnimalClass. java */public class interfaceAnimalClass implements interfaceAnimal {public void eat () {System. out. println ("m eats");} public void travel () {System. out. println ("m travels");} public static void main (String args []) {interfaceAnimalClass m = new interfaceAnimalClass (); m. eat (); m. travel ();}}
Note the following when rewriting the methods declared in the interface:
- The class must have the same method name when rewriting the method, and the return value type should be the same or compatible.
- If the class implementing the interface is an abstract class, there is no need to implement the interface method.
Note the following when implementing the interface:
- A class can implement multiple interfaces at the same time.
- A class can inherit only one class, but can implement multiple interfaces.
- One interface can inherit another interface, which is similar to the inheritance between classes.
Interface inheritance:
// File name: Sports. javapublic interface Sports {public void setHomeTeam (String name); public void setVisitingTeam (String name);} // file name: Football. javapublic interface Football extends Sports {public void homeTeamScored (int points); public void visitingTeamScored (int points); public void endOfQuarter (int quarter );}
The class implementing the Football interface must implement five methods, two of which are from the Sports interface.