Home > DeveloperSection > Articles > Interface in Java

Interface in Java


Java Java 
Ratings:
0 Comment(s)
 612  View(s)
Rate this:

Interface in Java

An interface in the Java programming language is an abstract type that is used to specify an interface (in the generic sense of the term) that classes must implement.

An interface is similar to a class in the following ways:

·         An interface contains number of methods, not body of method.

·         An interface is written in a file with a .java extension as same as class name extension.

·         The bytecode of an interface appears in a .class file.

·         Interfaces appear in packages, and their corresponding bytecode file must be in a directory structure that matches the package name.

A Java class can only extend one parent class. Multiple inheritance is not allowed. Interfaces are not classes, however, and an interface can extend more than one parent interface.

For example

Public interface MyInterface extends Class1, Class2  {

}

For access interface in class use below syntax

class Sample implements MyInterface

 

Rules for Interfaces:

·         An interface is implicitly abstract. You do not need to use the abstract keyword when declaring an interface.

·         Each method in an interface is also implicitly abstract, so the abstract keyword is not needed.

·         Methods in an interface are implicitly public.

·         Interface cannot be declared as private, protected or transient.

·         Variables declared in interface are public, static and final by default.

Relationship between classes and interface

 

Here I am creating a sample of multiple interfaces

interface Interface1 {

     public void demo();

}

 

interface Interface2 {

     public int Addition(int a, int b);

}

 

class Sample {

 

     public static void main(String arg[]) {

           Sample2 sam2 = new Sample2();

           sam2.demo();

           System.out.print(" Addition -: " + sam2.Addition(5, 6));

 

     }

 

}

 

class Sample2 implements Interface1, Interface2 {

     @Override

     public void demo() {

           // TODO Auto-generated method stub

           System.out.println("Interface1 Method");

 

     }

 

     @Override

     public int Addition(int a, int b) {

           // TODO Auto-generated method stub

           a = a + b;

           return a;

 

     }

}

 

Output-:

Interface1 Method

 Addition -: 11

 

 


Don't want to miss updates? Please click the below button!

Follow MindStick