go to previous page   go to home page   go to next page

Answer:


Two Files

// HelloObject.java
//
public class HelloObject
{
  // method definition
  public void speak()
  {
    System.out.println("Hello from an object!");
  }
}
// HelloTester.java
//
public class HelloTester
{
  public static void main ( String[] args )
  {
    HelloObject anObject = new HelloObject();
    
    anObject.speak();
  }
}

Some programmers prefer to place just one class per file, as above. Name each file as the class name followed by .java and now all classes can be declared public. The class containing main() must be declared public.

Here is an example run where each class is in a separate file. Follow the java command with the name of the file that contains main() .

C:\JavaCode>javac HelloTester.java HelloObject.java
C:\JavaCode>java HelloTester
Hello from an object!
C:\JavaCode>

You don't need to mention the second file in the javac command line. If it is in the same directory the Java compiler will find it and compile it if needed.

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

QUESTION 8:

Could the main() method in this program construct several objects of class HelloObject?


go to previous page   go to home page   go to next page