Java Java Data Structures Organizing Data Interfaces

Didn't get interface

I didn't get nothing about interface! please can somebody help me to understand this? :(

1 Answer

Ryan Sherry
Ryan Sherry
12,449 Points

Hi Yadin,

I am happy try and help shed some light on interfaces.

From what I have gathered so far in our classes and in my personal learning, an interface is like a contract and it defines what variables and methods must be created if you decide you want a class to implement it. When you create an interface, it is like creating a class but the methods don't have bodies and the variables are not instantiated. Here is an example:

public interface fillWaterBottle { public static final int MAX_WATER; public int waterLevel; public void fillWaterBottle(); }

In the interface above, if we want one of our classes to implement it, we must follow the rules and adhere to the contract by creating a public void fillWaterBottle() method in our class. The cool thing is that we can decide what we want the method to actually do:

public class waterBottle implements fillWaterBottle { public static final int MAX_WATER = 10; public int waterLevel = 0; public void fillWaterBottle() { waterLevel = MAX_Water; } }

I hope this helps!

Thanks Ryan for the clear explanation!