Do you expect that a class definition will have its own state and behavior?

A good answer might be:

Yes. A class definition will have its own variables (state), and will have its own methods (behavior.)

Static Methods

The methods that a class definition has are called static methods. (Sometimes they are called class methods, but this is confusing.) A static method is a characteristic of a class, not of the objects it has created.

Important: A program can execute a static method without first creating an object! All other methods (not static) must be part of an object, so an object must exist before they can be executed.

Here is the example program again:
// The file stringTester.java
//
class stringTester
{

  public static void main ( String[] args )
  {
    String str1;   // str1 is a reference 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");
  }
}

This is an application, similar to many you have seen so far, but now I can give a better explanation about what is going on. Assume that a file named stringTester.java contains the above characters.

  • The file defines a class called stringTester.
  • The class has a static method called main().
  • Since main() is a static method, it belongs with the class, not with any object made from the class.
    • Since main() is a static method, there will be only one main() method.
  • After the file has been compiled, the resulting bytecodes are executed by the Java virtual machine.
    • The user executes the program by typing java stringTester.
  • The Java virtual machine looks in the bytecode version of the class definition of stringTester for the main() method.
  • The main() method starts running, creates an object, invokes its length() method, and gets stuff done.

Remember the idea of object-oriented programming: an application consists of a collection of cooperating software objects who's methods are executed in a particular order to get something useful done. The steps listed above is how the collection of objects gets started. (In this case only one object was created.)

QUESTION 13:

Say that you create a file that contains the definition of a class, but the the class contains no main() method. Can the methods of this class ever be executed?

Click Here after you have answered the question