Unlike classes when making a method in an interface, you don’t
define a body. In fact you don’t even put code in an interface method. When
implementing an interface into a class you write (implements interface_name),
after the header of the class. This will force you to have all the methods that
the interface has. In eclipse the body of the methods will automatically be
added to the class. You then can add code to the method in your class telling
it what to do. If you want to implement multiple interfaces, separate the names
with a coma.
You can use that interface type to create new objects of
classes that have that interface implemented. When you make a new object with a
type interface, you no longer have access to all the methods in that class, you
only have access to the interface methods. When you call a method with a parameter
type interface, you must pass an object into a method that implements that
specific interface.
Here’s an analogy that may help you understand interfaces
better. Say you were making tons of different types of bikes. Each type of bike
has two wheels a frame, and handle bars. An interface would allow you to make methods
for each of those parts. Then when you make a class for a new type of bike you
can implement that interface. This will add all the methods (wheels, frame, and
handle bars) into the class. This will make sure your bike has all those parts.
No comments:
Post a Comment