Creating , implementing and extending interfaces
Creating , implementing and extending interfaces
To create an interface in Java, use the interface keyword followed by the interface name.
Here's an example:
public interface MyInterface {
void doSomething();
int calculate(int x, int y);
}
In this example, we've defined an interface named MyInterface with two abstract methods, doSomething and calculate.
Implement an Interface
To implement an interface in a class, use the implements keyword, followed by the interface name.
The implementing class must provide concrete implementations for all the methods declared in the interface.
Here's an example:
public class MyClass implements MyInterface {
@Override
public void doSomething() {
System.out.println("Doing something in MyClass");
}
@Override
public int calculate(int x, int y) {
return x + y;
}
}
In this example, the MyClass class implements the MyInterface interface and provides implementations for the doSomething and calculate methods
You can extend an interface in Java using the extends keyword. An interface can extend one or more other interfaces.
Here's an example of extending an interface:
public interface MyExtendedInterface extends MyInterface {
String getName();
}
In this example, the MyExtendedInterface interface extends the MyInterface interface. It inherits the abstract methods from MyInterface (doSomething and calculate) and adds a new abstract method, getName.
Now, when you create a class that implements MyExtendedInterface, it must provide concrete implementations for all the methods in both MyInterface and MyExtendedInterface.
public class MyExtendedClass implements MyExtendedInterface {
@Override
public void doSomething() {
System.out.println("Doing something in MyExtendedClass");
}
@Override
public int calculate(int x, int y) {
return x * y;
}
@Override
public String getName() {
return "MyExtendedClass";
}
}
In this example, MyExtendedClass implements MyExtendedInterface, which extends MyInterface. Therefore, it must provide implementations for all the methods in both interfaces (doSomething, calculate, and getName).