If you are acquainted with the syntax of Class so getting the Java Interface syntax wouldn’t be difficult. Java Interface looks similar to the class but it is different from the class in many aspects. In interface you can only declare the abstract method, you cannot define it. As by its name you can conclude that in the interface, we deal with only the interface of the methods inside interface we do not define what that method definition.

//Syntax of Java interface
interface interface_name
{
int X;
void method1();
void method2(); // inside the interface we only declare the method.
}

The above code is the syntax of Java Interface. At first glance, it looks similar to Class. As like class, in the interface, we use interface keyword to define the interface and just after that we declare the interface name. In the above syntax, it is clearly shown that the interface only contains the methods declaration. You can’t define the method definition inside the interface. So, the question arises where to define the interface method? and how to access those?

For that, you need to implement the Interface with the help of classes.

In class, if you declare a function, the access modifier of that function by default is of Package level it would neither be public nor be protected or private, but in the case of interface, all the members are public access modifier.

Some Important Points of Interface:

  • In the interface, all members are public by default.
  • All the method inside the interface is public and abstract implicitly.
  • The fields (variables inside the interface) of the interface are implicitly public, static and final.
  • The functions declared in the interface are not static.
  • You cannot create an interface object
  • The interface does not have the constructor
  • Though we cannot create the object of any interface we can create the object reference.

The implementation of the interface is like inheritance of classes. In Java, the class does not support the case of multiple inheritances so to overcome this constraint in Java we use Java interface.

// Syntax to implement the interface
interface Mammals
{
void eat();
void speak();
}
class dog implements Mammals
{
public void eat()
{
System.out.println(“I am a cat and I Eat fish”);
}
public void speak()
{
System.out.println(“ Meow ”);
}
}

Why do we need Interface?

  • Java does not have the concept of multiple inheritances with the help of interface java can overcome this problem.
  • To achieve Loose Coupling.
  • Total abstraction can be achieved by using a Java interface.

Leave a Reply

Your email address will not be published. Required fields are marked *