Objects |
| BASIC |
A class describes objects (also called instances), and every object "belongs to" (is described by) some class; the class is the type of that object. All but the very simplest programs work by creating objects and letting the objects interact.
An object is created by calling (with the keyword new) a constructor
for that type of object. For example, assume the class Person is
defined as follows:
class Person { // instance variables String name; int age; // constructor public Person(String name) { this.name = name; } // method public void birthday() { age = age + 1; } }
In this example the Person class has a constructor that takes
a String as an argument, so you might create new
instances of Person as follows:
Person candidate = new Person("Hillary Clinton"); Person favoriteAuthor = new Person("Terry Pratchett")
Important but difficult concept:
You can see that the candidate object has a name
and age, and the favoriteAuthor object has a (separate
and probably different) name and age. Yet inside
the class definition the birthday() method just refers to age--so
whose age is this?
The answer is that you don't just "call the birthday() method."
Instead, you tell some particular object to execute its birthday()
method. You might say candidate.birthday(), meaning "Candidate,
have a birthday," in which case the Person with the name "Hillary
Clinton" would add one to its own age variable. If you said
favoriteAuthor.birthday(), the Person with the name "Terry
Pratchett" would add one to its age variable.
In short, an object knows its own variables and executes its own methods.
The fields and methods of a class can be accessed by "dot notation," for example,
candidate.birthday(); = new Person("Terry Pratchett"); System.out.println(candidate.name + " is now " + candidate.age;
A little about static:
In Java, almost all work is done by objects. Objects "talk" to one another: One object sends a message to another object (possibly itself), and the second object responds by executing the method named in the message, and returning the result to the first object. However, when your program first starts up, no objects have yet been created. Hence, something special is needed to get everything started.
A static method is one that exists independently of any objects; instead, it belongs to the class in which it is defined. Unlike objects, all your classes exist right from the beginning of your program. This means that static variables and static methods exist and can be used.
Your program begins execution at a method declared as . This is possible because main,
being static, does not depend on some object for its existence. In a typical
program, your main method does little more than create an initial object and
send it some initial message.