Last week, I
introduced abstract class in my blog post. This time, I will introduce interface,
which is somewhat similar to abstract class and inheritance. An interface is a
collection of related methods, but these methods do not have implementations.
They only have return type, method name, and parameter. In addition, all of the
methods in an interface are public and abstract, so you don’t have to include
modifier.
Unlike inheritance,
which defines is-a relationships, an interface can actually be implemented by
classes that represent very different objects. However, these objects must
share some capabilities or features that are expressed in the methods of the
interface. For example, an interface called Runnable includes a method Run, which stimulates object’s running.
Classes that can implement this interface may be Dog,
Car, Person, etc. However, the class Bird cannot implement this interface because birds do not
run but fly.
To be more clear,
let’s see the following code.
public interface
Runnable {
void Run();
}
public class Dog implements Run {
…
So
why do we use interface in programming? Interface provides a framework of
behavior for any class. It also has the advantages suggested in the picture.
---------------------------------------------------------------------------------
Writing References:
1.Barron's AP Computer Science
Picture References:
1.https://www.prsblog.com/wp-content/uploads/2016/06/interface-in-java.png
2.http://csharpcorner.mindcrackerinc.netdna-cdn.com/UploadFile/9a9e6f/interface-keyword-in-java/Images/interface%20in%20Java.jpg
1.Barron's AP Computer Science
Picture References:
1.https://www.prsblog.com/wp-content/uploads/2016/06/interface-in-java.png
2.http://csharpcorner.mindcrackerinc.netdna-cdn.com/UploadFile/9a9e6f/interface-keyword-in-java/Images/interface%20in%20Java.jpg


No comments:
Post a Comment