Interface (interface) can be thought of as a pure abstract class. He allows the creator to specify the basic form of a class: The method name, the self-compiled scale, and the return type, but does not specify the method body. Interfaces also contain data members, but they all default to static and final. That is, the interface provides details only and does not provide implementation details. All of the methods in the interface are abstract, and these abstract methods are accomplished by implementing different classes of the interface, in which the interface class variables can represent any object that implements the interface class, which can be implemented dynamically and hides the implementation details.
The interface syntax uses the interface keyword declaration, declaring only the class method prototype, without defining a direct method class tolerance, in the following format:
[Interface modifier] Interface interface name [<type>] [Extends parent class name]{
....//Method prototype
}
It is important to note that in an interface declaration, Java allows the final keyword to be omitted from the declaring data member, the public of the method, and the abstract keyword. As follows:
Interface shape2d{final Double pi = 3.14;public abstract double area ();}
You can omit the keyword directly:
Interface shape2d{double pi = 3.14;double area ();}
Interface implementations, interfaces naturally cannot use the new operator as a generic class to produce an object. The process of constructing a class using an interface is called an interface implementation. Implementing the interface requires the Implements keyword, with the following syntax:
Class modifier class Name implements interface name {
...//How to Implement Interface
}
The following example implements Shape2d.
Import static Java.lang.math.*;interface shape2d{final double pi = 3.14;public abstract double area ();} Class Circle implements shape2d{private double radius;p ublic Circle (double r) {radius = R;} Public double area () {return pi*radius*radius;}} Class Rectangle implements Shape2d{private double Width;private double length;public Rectangle (double w,double l) {width = W;length = l;} Public double area () {return width*length;}} public class Test{public static void Main (String [] args) {shape2d circle = new Circle (2.0); shape2d rectangle = new Rectangle (3.0, 5.0); System.out.println (Circle.area ()); System.out.println (Rectangle.area ());}}
Interfaces in Java