This article describes the basic use and simple concepts of interfaces in Java. Interfaces are a bit like abstract classes, interfaces are not classes, interfaces simply declare methods, and there is no specific implementation. In the Java programming language is an abstract type, which is a collection of abstract methods, and interfaces are usually declared with interface. A class inherits the abstract method of an interface by inheriting the interface. The interface cannot be instantiated, but it 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.
1. First to understand the declaration of the interface
In Java, the interface is declared with interface, and classes are declared with class.
Package Lesson01;
Public interface Student {
public int getage ();
}
2. Implementation of the interface
interface implementation, you need to inherit the interface of the class to override the method to implement.
Package Lesson01;
public class Student_abc implements Student {
public int getage () {
return 15;
}
}
The implementation of the interface in Java requires the Implements keyword, followed by the interface after the keyword.
3. When to use implements and extends
1) If the front and back two are class, then use extends
2) If the previous one is class and the latter one is interface, then use implements
3) If the front and back two are interface, use a extends.
Java Foundation 14: Interfaces