We are almost ready to take a deep dive into some more data structures—so far we have seen an array—but before we do, we need to talk about what an interface is in Java. The way the common person uses “interface” when dealing with computers, what is typically meant is the GUI, or the “graphical user interface.” These are all the displays, and buttons and arrows, and icons you click on, scroll through, and interact with to do things with a computer. There is a command much lower level than the typical user (that is, closer to the CPU) that starts a browser window, but you don’t need to know it; double-clicking on the browser icon gets interpreted as “the user wants to run the command to start the browser” because that information gets passed through the GUI down the right channels.
Every class we have written or used so far has been “concrete.” In Java, the opposite of this is “abstract,” which is a reserved word (“concrete” is not). When a class is abstract—Puppy, for example—you cannot create any Puppy objects. These classes can have methods that have no bodies, which are called abstract methods (declared, as with the classes, with the keyword “abstract”, as in public abstract class Puppy, and so on). Abstract methods have signatures that include “abstract” in the position after the access modifier, and they end with a semicolon. They include no implementation.
Abstract classes, on their own, are useless. They need other classes to extend them. Those that do must implement the abstract methods in the abstract class they extend. Not every method in an abstract class must be abstract; abstract classes, therefore, can have some concrete methods, which are implemented normally as we have always done.
Interfaces, on the other hand, are (by default) entirely abstract contracts to implement certain methods to create some object. There is a key difference between interfaces and abstract classes, beyond the fact that everything is abstract in one but not necessarily in the other: while you can only extend (inherit from) one class, you can implement as many interfaces as you would like. Simply comma-separate the interfaces, like so:
public class MyClass implements InterfaceA, InterfaceB {
@Override
public void methodA() {
// Implementation for InterfaceA's method
}
@Override
public void methodB() {
// Implementation for InterfaceB's method
}
}
By doing this, whoever wrote the code is committing to implement all the methods in InterfaceA and InterfaceB. I don’t particularly need to know or care what they are—I just know that’s true, since that’s the contract you make when you declare you’re implementing an interface.
Some of the most important ones you’ll use—which are all data structures—are the following:
This is the order in which we’ll go through these fundamental data structures—and then we’ll go through the Stack class (which is concrete) for a fourth critical data structure.
No comments:
Post a Comment