Source Files
Lesson:
Main Points:
- All java source files must end with the .java extension.
- A source file should generally contain at most one top-level public
class definition.
- If a public class is present, the class name should match the unextended
filename.
- A source file may contain an unlimited number of non-public class
definitions.
- There are three top-level elements that may appear in a file: package
declaration, import statements, class definitions.
- Whitespace and comments may appear anywhere in a source file.
The three top level elements that may appear in a file include: package
declaration, import statements, and class definitions. None of these
elements is required. If they are present they must appear in the following
order:
- package declaration
- import statements
- class definitions
Here is an example:
// Package declaration
package exam.prepguide;
// Imports
import java.awt.Button; // imports a specific class
import java.util.*; // imports an entire package
// Class definition
public class Test { ... }
Here is an example that will actually run on a web page:
//--------------------------------------------
// ex1.java - First example of certification unit
// shows class declarations and use of import statement.
//--------------------------------------------
//import statements: the asterisk imports entire package
import java.awt.*;
import java.applet.*;
//class declaration with extends keyword
public class ex1 extends Applet{
Dimension d;
public void init(){
setBackground(Color.yellow);
d=getSize();
}
public void paint(Graphics g){
g.setColor(Color.red);
g.drawRect(5,5,d.width-10,d.height-10);
g.drawString("This example shows the use of import statements,",20,20);
g.drawString("and a class declaration. There are also some", 20, 40);
g.drawString("comments in this source code. Read them.",20,60);
}
}
Here is the applet actually running on this page:
Look at the source for this page to review how to set up an applet tag.
None of this should be new to you at this point. The only thing you may not
be familiar with is the package declaration.
Assignment:
Create an applet which you call yourname01.java (actually use YOUR NAME, for
instance, if your name is Roger, call it roger01.java). In this applet
import the awt and the applet packages. Use comments before your import
statements and your class declaration. Your applet will have the background
color set to blue and you will draw three rectangles in yellow and your
first name will be in the first rectangle, your middle name in the second,
and your last name in the third. All three parts of your name should be in
white.
Present your code along with your applet on a web page.