interface
From an abstract point of view, as a template of a class, an abstract class can contain both abstract methods and non-abstract methods, limiting the design of subclasses
Interface, which only contains abstract methods and constants, can restrict subclasses more standardized
Definition of interface
Composed of two parts: abstract declaration and interface body
Format: [public] interface interface name {declaration and definition of constant data member, declaration of abstract method}
note
- The constants defined in the interface body are modified by "public static final" by default and do not need to be specified
- The declared method, the system defaults to "public abstract" modification, no need to specify
Implementation of the interface
In the declaration part of the class, use the keyword implements to declare that this class implements an interface. If there are multiple interfaces, separate the interface names with commas.
The format is as follows:
class class [extends parent class name] implements interface 1, interface 2,… {implement all abstract methods in the interface}
The difference between interface and abstract class
grammar | interface interface name {} | abstract abstract class name {} |
---|---|---|
Instantiate | Cannot be instantiated between | Cannot be instantiated between |
method | The methods in the interface are all abstract methods | Not necessarily all abstract methods |
inherit | A class can implement multiple interfaces | A subclass can only have one direct parent |
Member permissions | All members are public | Not necessarily all public |