A Tiny Example

Classic programmed-learning exercises, refreshed for modern Java and presented in the current MrStyner.com portfolio style.

Modern Java noteThis archive has been refreshed for Java 25 LTS. Core language concepts remain useful, while outdated setup instructions and browser-era Java are labeled or replaced. Java 26 is the current feature release; Java 25 is used here as the stable teaching baseline.
go to previous page   go to home page   go to next page

Answer:

No. You need only one main() method for the Java virtual machine to use in starting your program.

A Tiny Example

class HelloObject
{
  // method definition
  void speak()
  {
    System.out.println("Hello from an object!");
  }
}

class HelloTester
{
  public static void main ( String[] args )
  {
    HelloObject anObject = new HelloObject();
    
    anObject.speak();
  }
}

Above is a complete program which includes two class definitions. The definition of class HelloObject includes a method but no instance variables, so objects of class HelloObject have no instance variables. The class does have a constructor but it is not explicitly defined in the code (this will be discussed further).

The definition of class HelloTester contains only the static main() method. When the main() method starts, it constructs a HelloObject and then invokes that object's speak() method.

Remember that name of the file must match the name of the class that contains the main() method. (Also remember that upper and lower case are important both in the file name and in the class name.) Here is an example run:

C:/>javac HelloTester.java
C:/>java HelloTester
Hello from an object!
C:/>

QUESTION 7:

  • What two classes are defined in this code?
  • What method is defined in the first class?