Interface in Java
Code 1:
public class User1 implements MyInterface { @Override public void doCalculation() { } } public class User2 implements MyInterface { @Override public void doCalculation() { } } interface MyInterface { public void doCalculation(); }
Code 2:
public class User1 { public void doCalculation() { } } public class User2 { public void doCalculation() { } }
In my code 1, I have a myinterface, which has an empty method docalculation() The docalculation () is used by user1 and user2 by implementing myinterface
In my code 2, I have two different classes that define the docalculation () method
In both code1 and code2 cases, I have to write my own implementation My method docalculation () is just an empty method
So what does myinterface do here?
>It only provides the method name or skeleton (the only advantage of the interface)? > Or will I save any memory when using myinterface? > Really, it only provides empty methods for the classes that implement it, so why don't I define it myself, as I did in code2. > Moreover, the user interface has more advantages
Solution
Interfaces are used a lot because they are basically blueprints for what your class should be able to do
For example, if you are writing a video game with characters, you can use an interface to save all the methods that a character should have
for example
public interface Character { public void doAction(); }
You have 2 roles, such as allies and enemies
public class Ally implements Character { public void doAction() { System.out.println("Defend"); } } public class Enemy implements Character { public void doAction() { System.out.println("Attack"); } }
As you can see, both classes implement interfaces, but they have different operations Now you can create a role that implements your interface and lets it perform its operations Depending on whether it is an enemy or an ally, it will perform different actions
public Character ally = new Ally(); public Character enemy = new Enemy();
In your main program, you can create a method to accept any object that implements your interface and let it perform its operations without knowing what type of character it is
void characterDoAction(Character char) { char.doAction(); }
If you are willing to provide Federation for this method, the output will be:
Defend
If you give the enemy of this method, the output will be:
Attack
I hope this is a good enough example to help you understand the benefits of using interfaces