Do you know where spotify gets it's music from? Well, there are is a list of methods that it uses to find your music for you. Whether or not you know how or where spotify gets its music from, it still will play music for you. This is called an Interface, and as you may have guessed, you can use them in Java.
In Java, an Interface is a piece of code that you write that will give you a list of methods which the classes that implement it must include. Please note that this is just a list of methods, and not the methods themselves. If you implement an Interface into your code's class, you are saying that this class will define and write all the methods that the interface lists. This could be useful if you are writing classes for different shapes on a grid. Each shape could inherit from a super class that gives you the coordinates of the shape, but the area of different shapes is determined in different ways. This means that you should have an interface that says that all member classes must have a get area method. To give the shapes this Interface, you will type:
class name implements size{
where name is the shape that you want to implement this interface for. The size interface code would look something like this:
public interface size{
public double getArea();
}
please note that an interface can have more than one method inside of it. This would look something like this:
public interface size{
public double getArea();
public void grow(int factor);
public void shrink(int factor);
}
I hope that you have learned a thing or two about interfaces in java, and feel free to ask me questions in the comments.
No comments:
Post a Comment