A class that implements a certain interface can call methods in the interface. An interface can be understood as an ability. For example, every animal has the ability to bark, but each animal has a different cry. The ability to bark can be defined as an interface.
1. Create projects and packages
Open Eclipse and select File→New→Project. In the Select a wizard window that pops up, select Java Project and click Next.
Enter the project name and click Next (it is recommended to follow the naming rules)
Right-click the new project, Select New→Package in order. After naming the package, click Next.
2. Create an interface
Right-click the package and select New→Interface.
After naming the interface ShoutAbility, click Finish. (Shouting capability interface)
As shown below, define the interface shout() method (keep good habits and add comments), and press Ctrl S to save.
3. Create an interface implementation class
Right-click the package, select New→Class, and name the class AoShout ( Howling).
As shown below, AoShout implements the ShoutAbility interface. The keyword to implement the interface is implements, and overrides the shout method of the interface. Press Ctrl S to save.
4. Call the interface method
Create a Bird class and define a constructor with parameters, using the interface type to define parameters .
When defining Bird's shout() method, you can use interface variables to call the interface method.
Press Ctrl S to save.
Create a test class, create an interface object using the interface implementation class AoShout, and then use the created bridShout object to create a bird object.
When calling the bird method, the method called to the interface will be executed, and the method of the implementation class will be found through the interface.
Notes
The methods of the interface are all abstract methods, and the methods must be implemented in the implementation class; a class can have multiple An interface (capability); the first letter of the class name must be capitalized.
php Chinese website, a large number of free Java introductory tutorials, welcome to learn online!
The above is the detailed content of How to call java interface. For more information, please follow other related articles on the PHP Chinese website!