A java interface is instructions on how a class should be built. An interface will only contain method headers and fields(variables), but the methods will have no implementation. In short, an interface describes what all the methods should be, but doesn’t actually write them.
If an interface just writes what a class should be, but doesn’t actually run any code. Why would we write them. Think back to your group project. Each of you might have been writing a piece of the code that needed to fit inside a larger program. By writing interfaces, you can know what your partners methods would look like, so that they can predictably fit inside the bigger picture.
Interfaces also provide common variables that should have certain values and be unchanged. If I wrote an interface for a circle, I would most likely want to give it a global variable for the value of PI. If I use the keyword final then that value cannot be changed.
1. To create an interface you will need the java keyword interface. This keyword will replace class.
2. Then include any global variables that your interface will need. These can have actual values.
3. Then include all the method signatures with a semicolon at the end instead of {}.
Interfaces cannot be instantiated like classes, they can only be implemented. To implement an interface means to actually write what should go inside all the methods.
1. To implement one, you need to create a class and then on the same line use the java keyword implements and then the name of the class.
2. Then you need to create all of the methods from the interface. You can have more methods than those, but you cannot leave out any of the methods from the interface. For example, if you say that there are 5 methods with specific return types, visibility, names, parameters, then all 5 need to be implemented exactly that way.
3. Any of the variables made in the interface are now accessible so you do not need to recreate any of those.
1. You can implement multiple interfaces in the same class.
2. You cannot create an instance of the interface, you have to create a class that implements the interface and then you can create an instance of that class.
Create an interface that represents a car & then implement it.
1. The car interface should have several final variables declared and assigned: number_of_doors, number_of_wheels. Choose the appropriate values for those.
2. The car interface should have several method signatures: getCarName(), setCarName(), getEngineCylinders(), setEngineCylinders(), getTopSpeed(), setTopSpeed().
3. Implement the interface and create your favorite car.
4. You should add the global variables needed for the getters/setters: carName, topSpeed, engineCylinders, etc.
5. Test in main.