Monday 13 March 2017

Applet Fundamentals, The transient and volatile Modifiers & Using instanceof - Java Tutorials

Applet Fundamentals

All of the preceding examples in this book have been Java applications. However, applications constitute only one class of Java programs. Another type of program is the applet. As mentioned in Chapter 1, applets are small applications that are accessed on an Internet server, transported over the Internet, automatically installed, and run as part of a Web document. After an applet arrives on the client, it has limited access to resources, so that it can produce an arbitrary multimedia user interface and run complex computations without introducing the risk of viruses or breaching data integrity.

Many of the issues connected with the creation and use of applets are found in Part II, when the applet package is examined. However, the fundamentals connected to the creation of an applet are presented here, because applets are not structured in the same way as the programs that have been used thus far. As you will see, applets differ from applications in several key areas.

Let’s begin with the simple applet shown here:

  import java.awt.*;
  import java.applet.*;

  public class SimpleApplet extends Applet {
    public void paint(Graphics g) {
      g.drawString("A Simple Applet", 20, 20);
    }
  }

This applet begins with two import statements. The first imports the Abstract Window Toolkit (AWT) classes. Applets interact with the user through the AWT, not through the console-based I/O classes. The AWT contains support for a window-based, graphical interface. As you might expect, the AWT is quite large and sophisticated, and a complete discussion of it consumes several chapters in Part II of this book. Fortunately, this simple applet makes very limited use of the AWT. The second import statement imports the applet package, which contains the class Applet. Every applet that you create must be a subclass of Applet.

The next line in the program declares the class SimpleApplet. This class must be declared as public, because it will be accessed by code that is outside the program.

Inside SimpleApplet, paint( ) is declared. This method is defined by the AWT and must be overridden by the applet. paint( ) is called each time that the applet must redisplay its output. This situation can occur for several reasons. For example, the window in which the applet is running can be overwritten by another window and then uncovered. Or, the applet window can be minimized and then restored. paint( ) is also called when the applet begins execution. Whatever the cause, whenever the applet must redraw its output, paint( ) is called. The paint( ) method has one parameter of type Graphics. This parameter contains the graphics context, which describes the graphics environment in which the applet is running. This context is used whenever output to the applet is required.

Inside paint( ) is a call to drawString( ), which is a member of the Graphics class. This method outputs a string beginning at the specified X,Y location. It has the following general form:

      void drawString(String message, int x, int y)

Here, message is the string to be output beginning at x,y. In a Java window, the upper-left corner is location 0,0. The call to drawString( ) in the applet causes the message “A Simple Applet” to be displayed beginning at location 20,20.

Notice that the applet does not have a main( ) method. Unlike Java programs, applets do not begin execution at main( ). In fact, most applets don’t even have a main( ) method. Instead, an applet begins execution when the name of its class is passed to an applet viewer or to a network browser.

After you enter the source code for SimpleApplet, compile in the same way that you have been compiling programs. However, running SimpleApplet involves a different process. In fact, there are two ways in which you can run an applet:
  • Executing the applet within a Java-compatible Web browser.
  • Using an applet viewer, such as the standard SDK tool, appletviewer. An applet viewer executes your applet in a window. This is generally the fastest and easiest way to test your applet.

Each of these methods is described next. To execute an applet in a Web browser, you need to write a short HTML text file that contains the appropriate APPLET tag. Here is the HTML file that executes
SimpleApplet:

  <applet code="SimpleApplet" width=200 height=60>
  </applet>

The width and height statements specify the dimensions of the display area used by the applet. (The APPLET tag contains several other options that are examined more closely in Part II.) After you create this file, you can execute your browser and then load this file, which causes SimpleApplet to be executed.

To execute SimpleApplet with an applet viewer, you may also execute the HTML file shown earlier. For example, if the preceding HTML file is called RunApp.html, then the following command line will run SimpleApplet:

      C:\>appletviewer RunApp.html

However, a more convenient method exists that you can use to speed up testing. Simply include a comment at the head of your Java source code file that contains the APPLET tag. By doing so, your code is documented with a prototype of the necessary HTML statements, and you can test your compiled applet merely by starting the applet viewer with your Java source code file. If you use this method, the SimpleApplet source file looks like this:

  import java.awt.*;
  import java.applet.*;
  /*
  <applet code="SimpleApplet" width=200 height=60>
  </applet>
  */

  public class SimpleApplet extends Applet {
    public void paint(Graphics g) {
      g.drawString("A Simple Applet", 20, 20);
    }
  }

In general, you can quickly iterate through applet development by using these three steps:
  1. Edit a Java source file.
  2. Compile your program.
  3. Execute the applet viewer, specifying the name of your applet’s source file. The applet viewer will encounter the APPLET tag within the comment and execute your applet.

While the subject of applets is more fully discussed later in this book, here are the key points that you should remember now:
  • Applets do not need a main( ) method.
  • Applets must be run under an applet viewer or a Java-compatible browser.
  • User I/O is not accomplished with Java’s stream I/O classes. Instead, applets use the interface provided by the AWT.





The transient and volatile Modifiers

Java defines two interesting type modifiers: transient and volatile. These modifiers are used to handle somewhat specialized situations. When an instance variable is declared as transient, then its value need not persist when an object is stored. For example:

  class T {
    transient int a; // will not persist
    int b; // will persist
  }

Here, if an object of type T is written to a persistent storage area, the contents of a would not be saved, but the contents of b would.

The volatile modifier tells the compiler that the variable modified by volatile can be changed unexpectedly by other parts of your program. One of these situations involves multithreaded programs. (You saw an example of this in Chapter 11.) In a multithreaded program, sometimes, two or more threads share the same instance variable. For efficiency considerations, each thread can keep its own, private copy of such a shared variable. The real (or master) copy of the variable is updated at various times, such as when a synchronized method is entered. While this approach works fine, it may be inefficient at times. In some cases, all that really matters is that the master copy of a variable always reflects its current state. To ensure this, simply specify the variable as volatile, which tells the compiler that it must always use the master copy of a volatile variable (or, at least, always keep any private copies up to date with the master copy, and vice versa). Also, accesses to the master variable must be executed in the precise order in which they are executed on any private copy.

volatile in Java has, more or less, the same meaning that it has in C/C++/C#.




Using instanceof

Sometimes, knowing the type of an object during run time is useful. For example, you might have one thread of execution that generates various types of objects, and another thread that processes these objects. In this situation, it might be useful for the processing thread to know the type of each object when it receives it. Another situation in which knowledge of an object’s type at run time is important involves casting. In Java, an invalid cast causes a run-time error. Many invalid casts can be caught at compile time. However, casts involving class hierarchies can produce invalid casts that can be detected only at run time. For example, a superclass called A can produce two subclasses, called B
and C. Thus, casting a B object into type A or casting a C object into type A is legal, but casting a B object into type C (or vice versa) isn’t legal. Because an object of type A can refer to objects of either B or C, how can you know, at run time, what type of object is actually being referred to before attempting the cast to type C? It could be an object of type A, B, or C. If it is an object of type B, a run-time exception will be thrown. Java provides the run-time operator instanceof to answer this question.

The instanceof operator has this general form:

      object instanceof type

Here, object is an instance of a class, and type is a class type. If object is of the specified type or can be cast into the specified type, then the instanceof operator evaluates to true. Otherwise, its result is false. Thus, instanceof is the means by which your program can obtain run-time type information about an object.

The following program demonstrates instanceof:

  // Demonstrate instanceof operator.
  class A {
    int i, j;
  }

  class B {
    int i, j;
  }

  class C extends A {
    int k;
  }

  class D extends A {
    int k;
  }
  
  class InstanceOf {
    public static void main(String args[]) {
      A a = new A();
      B b = new B();
      C c = new C();
      D d = new D();

      if(a instanceof A)
        System.out.println("a is instance of A");
      if(b instanceof B)
        System.out.println("b is instance of B");
      if(c instanceof C)
        System.out.println("c is instance of C");
      if(c instanceof A)
        System.out.println("c can be cast to A");

      if(a instanceof C)
        System.out.println("a can be cast to C");

      System.out.println();
      
      // compare types of derived types
      A ob;

      ob = d; // A reference to d
      System.out.println("ob now refers to d");
      if(ob instanceof D)
        System.out.println("ob is instance of D");

      System.out.println();

      ob = c; // A reference to c
      System.out.println("ob now refers to c");

      if(ob instanceof D)
        System.out.println("ob can be cast to D");
      else
        System.out.println("ob cannot be cast to D");

      if(ob instanceof A)
        System.out.println("ob can be cast to A");

      System.out.println();

      // all objects can be cast to Object
      if(a instanceof Object)
        System.out.println("a may be cast to Object");
      if(b instanceof Object)
        System.out.println("b may be cast to Object");
      if(c instanceof Object)
        System.out.println("c may be cast to Object");
      if(d instanceof Object)
        System.out.println("d may be cast to Object");
    }
  }

The output from this program is shown here:

  a is instance of A
  b is instance of B
  c is instance of C
  c can be cast to A
  ob now refers to d
  ob is instance of D

  ob now refers to c
  ob cannot be cast to D
  ob can be cast to A

  a may be cast to Object
  b may be cast to Object
  c may be cast to Object
  d may be cast to Object

The instanceof operator isn’t needed by most programs, because, generally, you know the type of object with which you are working. However, it can be very useful when you’re writing generalized routines that operate on objects of a complex class hierarchy.

No comments:

Post a Comment