Recommended: Sing it, brah! 5 fabulous songs for developers
JW's Top 5
Optimize with a SATA RAID Storage Solution
Range of capacities as low as $1250 per TB. Ideal if you currently rely on servers/disks/JBODs
Page 4 of 6
We've made a bit of a distinction here between general behavior, and behavior that is just related to getting and setting properties. We'll talk more about this later when we delve into the best way to actually program a type.
How do we use this type? Easy. We buy an alarm clock and bring it home. We set the current time and the alarm time. When it rings, we hit the snooze button (repeat five to six times), and we finally turn the alarm off and get out of bed.
The system depicted in this example is the core of OOP. We have types that represent the different kinds of things in our system, (the alarm clock type), and we have objects that are instances or examples of the types (we bought a particular alarm clock). Objects interact through their behaviors, sometimes resulting in changes in their properties, and ultimately (hopefully) do useful work. C'mon, you already knew this, otherwise you wouldn't be able to use your alarm clock, and you'd never get to work on time. Rewrite your resume -- you're an object-oriented programmer.
We've been talking abstractly until now about OOP. Let's shift back and see how OOP is done in Java. A class is used to define a new type in Java, and classes are central to the language. Everything happens within classes. All executable code exists in classes (generally in methods), and all data appears within a class (in variables within a class, and in variables in methods).
Classes are defined in a class definition. Here's a (simple and incomplete) definition for an AlarmClock class.
public class AlarmClock {
}
AlarmClock is the name of the class
{ starts the class body
} ends the class definition
public means shortly
It's time to create your first class, albeit one that doesn't do much yet. It will soon, though. Create a file called AlarmClock.java, and put in the code for the class definition above. Compile it using javac.
javac AlarmClock.java
Note that when a class definition starts with the keyword public, Java requires you to put the class definition (the Java source) into a file that starts with the name of the class. Hence,
we name our file AlarmClock.java because the class name is AlarmClock.
What can we do with this? Have we actually created an AlarmClock? Nope. Remember that a class (that defines a type in Java) is a blueprint for an object, but it's not the actual object.
A class definition is like a cookie cutter, but it's not a cookie. You create cookies by cutting some dough with the cookie
cutter. Similarly, we have to cut some objects from memory to create them. You create or instantiate objects in Java with an operator called new followed by the name of the class for which you want to create an instance. The syntax looks like this: