Every application so far in these notes has a line in it:
public static void main ( String[] args )
This is the header for the main method in the class being described.
When a Java application is being run, objects are created and their methods are invoked (are run.) To create an object, there needs to be a description of it.
A class is a description of a kind of object. A programmer may define a class using Java, or may use predefined classes that come in class libraries.
A class is merely a plan for a possible object (or objects.)
It does not by itself create any objects.
When a programmer wants to create an object
the new
operator is used with the name of the class.
Creating an object is called instantiation.
Here is a tiny application that instatiates (creates) an object
by following the plan in the class String
:
class StringTester { public static void main ( String[] args ) { String str1; // str1 is a variable that refers to an object, // but the object does not exist yet. int len; // len is a primitive variable of type int str1 = new String("Random Jottings"); // create an object of type String len = str1.length(); // invoke the object's method length() System.out.println("The string is " + len + " characters long"); } } |
When it is executed (as the program is running), the line
str1 = new String("Random Jottings");
creates an object by following the description in class String
.
The class String
is defined in the class library java.lang
that comes with the Java system.
The computer system finds a chunk of memory for the object,
lays out this memory according to the plan (the definition of String),
and puts data and methods into it.
The data in this String object will be the characters "Random Jottings"
and the methods will be the many methods that all String objects have.
One of these methods is length()
.
The variable str1
is used to refer to this object.
In other words, str1
gives the object a name.