![]() |
![]() |
Java Interface | |
Java Class vs Interface | |
Java Multiple Inheritance | |
Java Nested Interface |
Java Packages | |
Java Built in packages | |
Java Package Access Specifiers |
Introduction of Errors | |
Java Exceptions | |
Java Try Block | |
Java Catch Block | |
Java Finally Block | |
Java Throw Keyword | |
Java Throws Keyword | |
Java Builtin Exceptions | |
User Defined Exceptions |
Java Programs | |
Java Keywords Dictionary | |
Java Interview Questions |
Interface is also known as kind or type of a class. It contains only abstract methods and final fields.
Interface do not specify any code to implement methods or initialization of data. These are always implemented in the class which defines the implementation of these methods.
Interfaces are mostly used in java for following purposes
interface InterfaceName { // methods declarations return_type methodName1 (parameterList); return_type methodName2 (parameterList); . . return_type methodNameN (parameterList); // field declarations type final_field = value; type final_field2 = value; . . type final_fieldN = value; }
Variables
By default variables declared inside the interface becomes final fields. They must be initialized to constant value otherwise gives an error as the black field variable have not been intialized.
Methods
Interface contains only declaration of methods without writting its body with statements. By default declared methods are considered as a abstract methods. Easy class which implements that interface must write all methods body.
interface Mobile { int price = 5600; String brand = "MyPhone"; void displayDetails(); void startPhone(); } class PhoneUser implements Mobile { public void displayDetails() { System.out.println("\nPhone brand : "+brand); System.out.println("\nPhone price : "+price); } public void startPhone() { System.out.println("\nStarting the phone ..."); } public static void main(String args[]) { PhoneUser n1 = new PhoneUser(); n1.displayDetails(); n1.startPhone(); } }
In above example we have created interface Mobile, which is implemented in the class PhoneUser. All methods are implemented inside the class and called them using object of class.