Classes |
| BASIC |
A class is a description of objects; the objects are called the instances of that class. (The terms "object" and "instance" are often used interchangeably.)
Here is an example of a simple class Person:
public class Person { // instance variables String name; int age; // constructor public Person(String name) { this.name = name; } // method public void birthday() { age = age + 1; } }
This class itself does not represent a person; rather, it describes the characteristics that each person object must have:
name, which is probably different for each Person,age,Person (by giving them a name), andbirthday() message.New instances of this class are created using the keyword new,
for example,
Person candidate = new Person("Hillary Clinton"); Person favoriteAuthor = new Person("Terry Pratchett")
The fields and methods of a class can be accessed by "dot notation," for example,
candidate.birthday(); System.out.println(candidate.name + " is now " + candidate.age;
Java requires that each public class be in a separate
file, and that the file name is the class name with a .java extension.
For example, the Person class must be in a file named Person.java.
(For platform independence, capitalization must be correct.) It follows that
there can be only one public class in a file. It is conventional--and
good style--to put every class in a separate file, whether public
or not.
Also see Objects.
| INTERMEDIATE |