Java Interface is a programming construct that allows developers to define a set of methods that a class must implement. It is a way to achieve abstraction and polymorphism in Java. An interface is a collection of abstract methods and constants that can be implemented by any class. It defines a contract between the class and the outside world, specifying what methods the class must implement and what behavior it must exhibit.
Interfaces are used to define a set of methods that a class must implement, without specifying how those methods should be implemented. This allows for greater flexibility in the design of a program, as different classes can implement the same interface in different ways. Interfaces are also used to achieve multiple inheritance in Java, as a class can implement multiple interfaces.
Here is an example of a simple interface:
public interface MyInterface {
public void method1();
public void method2();
}
This interface defines two methods, method1()
and method2()
, that any class implementing this interface must implement. Note that the methods are declared without a body, as they are abstract methods.
Here is an example of a class that implements the MyInterface
interface:
public class MyClass implements MyInterface {
public void method1() {
System.out.println("Method 1");
}
public void method2() {
System.out.println("Method 2");
}
}
This class implements the MyInterface
interface and provides implementations for the method1()
and method2()
methods. Note that the class must implement all the methods defined in the interface.
Here is an example of how to use the MyClass
class:
MyInterface obj = new MyClass();
obj.method1();
obj.method2();
This code creates an instance of the MyClass
class and assigns it to a variable of type MyInterface
. This variable can be used to call the method1()
and method2()
methods, which are implemented by the MyClass
class.
Interfaces can also contain constants, which are public, static, and final by default. Here is an example:
public interface MyInterface {
public static final int MY_CONSTANT = 10;
public void method1();
public void method2();
}
This interface defines a constant MY_CONSTANT
, which can be accessed by any class that implements this interface.
Interfaces can also extend other interfaces, allowing for the creation of hierarchies of interfaces. Here is an example:
public interface MyInterface1 {
public void method1();
}
public interface MyInterface2 extends MyInterface1 {
public void method2();
}
This code defines two interfaces, MyInterface1
and MyInterface2
. MyInterface2
extends MyInterface1
, which means that any class implementing MyInterface2
must also implement the method1()
method defined in MyInterface1
.
Interfaces are an important part of Java programming, as they allow for greater flexibility and modularity in the design of a program. By defining a set of methods that a class must implement, interfaces provide a way to achieve abstraction and polymorphism in Java.