The demos below illustrate how to create a class object. This
can also by referred to as instantiating
(creating an instance of) a class.
For the demos here and in the rest of this chapter, we will use
the the applet
starter StartApplet2.java
and the application starter StartApp2.java.
Each includes the class Test
for inserting methods and data fields. In the main
routine, which is where the processing begins, we create an instance
of the Test
class and invoke its methods, access its data, etc..
The first applet - DataFieldApplet
- demonstrates a class with only a data field. In the init()
method we create an instance of class Test
and then use the reference "test"
and the "." operator to access the "i"
variable in the object:
DataFieldApplet.java
(Output goes to browser's Java
console.) |
public
class
DataFieldApplet extends
java.applet.Applet
{
public
void init ()
{
//Create an instance of the
Test class
Test test = new
Test();
// Access the variable i in
the Test object.
int
j = test.i;
System.out.println ("test.i = "+j);
System.out.println ();
}
//
Paint message in Applet window.
public void paint
(java.awt.Graphics g)
{ g.drawString ("DataFieldApplet", 20,
20); }
}
// Use Test to examine various aspects of class design
class
Test
{
int i = 5;
}
|
|
The second applet - MethodApplet
- demonstrates a class with both a data field and a method. In the
init() method
we create an instance of class Test
and then use the reference "test"
and the "." operator to access the "aMethod(int
j)" method in the object:
MethodApplet.java
(Output goes to browser's Java
console.) |
public
class
MethodApplet extends
java.applet.Applet
{
public
void init () {
//Create an instance of the
Test class
Test test = new
Test ();
// Invoke a method
test.aMethod
(3);
}
//
Paint message in Applet window.
public void paint
(java.awt.Graphics g)
{ g.drawString ("MethodApplet", 10, 20);
}
}
// Use Test to examine various aspects of class design
class
Test
{
int
i;
void
aMethod (int j) {
i = j;
System.out.println ("In aMethod()");
System.out.println ("i =
"+i);
System.out.println ();
}
}
|
|
Latest update: Oct. 19, 2004
|