Introduction to Java for the C++ Developer

Nancy Winnick Cluts
Microsoft Corporation

December 1996

Introduction

Java™ is a popular object-oriented programming (OOP) language used in Web development to provide system services not available through HTML. When you program with Java, you can create small applications, or applets, that run as plug-ins for your Web site. For the C or C++ developer, these plug-ins are akin to component object model (COM) objects and applets are akin to dynamic-link libraries (DLLs). With the applets, you can provide user-interface objects such as list boxes or buttons. This article covers the basics of Java for the Windows® C or C++ developer. I discuss the differences between Java and ActiveX™ and explain how Java runs in Internet Explorer 3.0. This article is based upon presentations given by Michael Connell and Daniel Jinguji for the Site Builder Conference, held in San Jose, California, on October 27–30, 1996.

Java Basics

Java is an object-oriented programming (OOP) language that compiles into what is referred to as byte code. Resident on a machine that runs a Java applet is an application—the Java virtual machine (VM)—that verifies and interprets these byte codes.

Java applets run in a protected space known as the sandbox. The sandbox prevents the applet from accessing files and selected system services, thus protecting the system from viruses that might be resident in an applet (written by some nasty developer—nobody you and I know). The idea is to limit the applet's access to the machine; however, this limitation can also lead to a limitation of functionality. If, for example, you need to write an applet that reads a file on the machine (or reads the registry), the sandbox walls will keep you out of the machine data. Alternatives to Java and the sandbox are ActiveX controls and signed applets.

I said that Java was an OOP language—a language, in other words, concerned with objects and their interactions. Within this framework, the class is the central element. A class represents a system object that is patterned and has an associated state and associated methods. Procedural programming (C, FORTRAN, Pascal, et al.), on the other hand, is focused on the steps involved in completing a process. The procedure itself, rather than the class, is the most important element, the procedure being the list of steps used to perform a defined task that is part of the whole list of tasks within the program.

For more information and pointers to Web sites that talk about Java, see the Microsoft Presents Java site at http://www.microsoft.com/java/.

Java and COM

Under Windows, the Java VM is an ActiveX component that exposes the Java class as an ActiveX component. The VM supports scripting, allows you to use other ActiveX components from Java, and allows other ActiveX components to use Java objects. This is done via the component object model (COM).

COM provides the infrastructure for software-component interaction. It is language independent and platform independent. COM is the basis for ActiveX technologies as well as for OLE and Automation. COM consists of interfaces (IUnknown being the most basic). All COM objects are registered in the system by their CLSID (class id) and are instantiated via the CreateInstance function. COM interfaces reside in type libraries and use a proxy-stub mechanism for communication.

If you are creating a COM object and want to call a Java applet, you can use Visual J++ to perform the following steps:

  1. Create an ODL/IDL description file.

  2. Create a type library.

  3. Implement your COM interface.

  4. Register the Java class via JAVAREG.

  5. Make the class available.

Classpath and Trusted Classpath

The Java VM finds class files by searching the classpath. If the file you need is not in the classpath, you can denote a trusted classpath, which is a path to classes outside of the sandbox. The user determines which classes are to be trusted and which are not when the user installs the class onto his or her machine.

A Simple Java Program

The simplest Java program is easy to read but no cause for celebration:

class OurApplet
{
}

Ooh. Now wasn't that special? No? Okay, so it's about as exciting as a minimal C program—let's go on.

The Class Keyword

Java uses a special keyword, class, that is a template for creating objects. You use this declaration to define a new type. Think of each object you create as an instantiation of a class.

There are four basic types (or modifiers) of classes:

Fields

Classes have fields that describe an object. This relationship is akin to the C "struct" in which you have different fields that describe a structure. There are a few intrinsic objects, such as bool, char, and int, but when you want to instantiate a nonintrinsic object, you need to use new to do so. The modifiers for each field are:

The example below shows a simple class with a couple of simple fields: one is the intrinsic, int, and the other is a special class, String, that needs to be instantiated via new.

public class OurApplet
{
 int xPosition = 20;
 string author = new String ("Me");
}

Methods

Classes use methods to communicate with other objects. Methods allow you to set or get information about the current state of the object. This type of implementation encapsulates the data for the class (that is, you can't get your grimy little fingers directly on the fields). In the example class above, you would want the class to support methods to get and set the xPosition and String fields within the class.

Like classes and fields, methods also have modifiers (public, private, etc.) that describe the scope of the method. When a method is final, it means subclasses can't override or hide the method.

Methods can return one value. This means that you can write a Get type of method that returns the xPosition, or you can return an error value. Consider the code below that implements a couple of simple methods, getPosition and putPosition, on the class shown above, OurApplet.

Public class OurApplet
{
 private int xPosition = 20;
 String author = new String("Me");
 public void putPosition(int x) {
  xPosition = x;
 }
 public int getPosition() {
  return xPosition;
 }
}

Inheritance

Java allows classes to inherit from other classes via the extends keyword. This means that you can base a new class on an existing class (called the base class). The new class, called the derived class, inherits its parent's state and methods. When you implement a derived class, you do not need to change or to have the source code for the base class.

All Java classes implicitly derive from the Object class, and applets derive from the java.applet.Applet class. This base class, java.applet.Applet, provides most of the basic functionality of an applet for "free."

Import

The import statement gives a class access to other classes that are defined elsewhere. For example, the statement:

import java.applet.Applet

in your applet gives your applet access to the Applet class. This is akin to the INCLUDE statement in C. The following code snippet demonstrates the addition of imports and inheritance to the example class, OurApplet. The example imports java.awt.* (which is the package that includes all graphical elements) and java.applet.Applet. It is derived from Applet and overrides the paint class within the class.

import java.awt.*;
import java.applet.Applet;
public class OurApplet extends Applet 
{
   private in xPosition = 20;
   String author = new String("Me");
   public void paint(Graphics g)
   {
      g.drawstring(author, xPosition, 50);
   }
}

C developers are used to the notion of libraries containing classes. Java classes and interfaces are grouped into packages. The following list contains some commonly used packages:

The Life Cycle of an Applet

The applet life cycle is controlled by four methods inherited from the Applet class:

In order to be defined as an applet, an applet must implement these four basic methods.

Adding a GUI Element to an Applet

Now that you know how to create a simple applet, you might want to add some graphical user interface (GUI) elements to it. To do this, you need to import java.awt.* or one of its derived classes. Then, add the class field for the desired object type (for example, a button), add() the object to the container, initialize the GUI object in init(), and add an event handler for your component. The following example shows the initialization of a button.

import java.awt.*;
import java.applet.Applet;
public class OurApplet extends Applet 
{
   Button OutButton;
   public void init()
   {
      OurButton = new Button("Click me!");
      add(ourButton);
   }
}

The code above initialized the button; now let's find an event handler for it. An event handler is a method that responds to messages from the outside world (for example, a button click). The following code is an example of an event handler that processes a button-down operation:

Public boolean action(Event evt, object what)
{
   if (evt.target == OurButton)
   {
      OurButton.setLabel("Clicked");
      return true;
   }
   else return false;
}

Low-level events—for example, mouseDown(), mouseUp(), mouseMove(), mouseDrag(), mouseEnter(), mouseExit(), keyDown(), and keyUp()—have their own handlers, which you can override. With these handlers you can change component behavior instead of just using it.

Arrays

Arrays are first-class objects in Java. The code below demonstrates two ways you can create an array:

Example 1:
int MyArray[];
MyArray = new int[25];
Example 2:
int MyMatrix[][];
MyMatrix = new int[4][];
for (int i = 0; i < 4; i++)
   MyMatrix[i] = new int[5];

Note that arrays in Java are not necessarily "square." You can actually code an array to have one element in the first row, two elements in the second, three in the third, and so on. Very odd. Use at your own risk.

All objects in Java are passed by reference. That is, you don't actually pass the variable itself but pass a reference to it to another method. When you pass an object as an argument to a function, you are passing the actual object and not the value. This means that the target function can alter the value of the object.

Using ActiveX Controls

You can use ActiveX controls, or other non-Java objects, from your Java applet. This allows you to access methods and properties from your Java source code. Using an ActiveX control in Java looks just like using another Java class. For example, the following code uses an RDO object:

import msrdo.*;
rdoInterface myRDO = (rdoInterface) new rdoObject;

Note that you can't use ActiveX controls on any platform other than Intel Windows 95 or Windows NT®. So, although this is way-cool functionality, it comes at the expense of portability.

Useful utilities

In order to mix and match Java with non-Java objects, you can use the Microsoft® Java Type Library Compiler to generate .class files from type libraries. This utility can be run from the command line via the command javatlb.exe. Visual J++™ also contains tools and the Java Type Library Wizard. The Summary.txt generated by the wizard contains useful information about the generated classes.

Another utility you might find useful is OLE2VW32.EXE. This tool allows you to browse existing ActiveX components, display a component's CLSID, and find scriptable methods for a class.

Scripting an Applet

Now that you know a little about creating your own Java applet (or understanding Java code that someone dumped in your lap), let's take a look at how you can use scripting to activate that applet. You can embed and control Java applets and ActiveX controls from within HTML using Visual Basic® Scripting Edition (also known as VB Script), Jscript™, or any ActiveX scripting language. You don't have to understand the source code to your applet or control in order to script it. Once you have the controls you want, it's simply a matter of laying out the controls on the HTML page and connecting them using ActiveX scripting. The example below shows an HTML page that has a spinning-world applet and a spin-button control embedded in its page. The example then uses scripting to activate the controls.

<html>
<body>
<!— Embed the spinning-world applet—>
<applet
   code=TestApplet.class ID=world
   width=100
   height=100 >
</applet>
<!— Embed a spin-button control —>
<OBJECT
   classid="clsid:79176FB0-B7F2-11CE-97EF-00AA006D2776"
   id=spinbtn >
</OBJECT>
<!— Create some HTML form buttons —>
<INPUT TYPE=button VALUE="Forward" NAME="BtnForward">
<INPUT TYPE=button VALUE="Reverse" NAME="BtnReverse">
<!— Create the handlers for our controls —>
<SCRIPT language = "VBScript">
<!—
Sub BtnForward_OnClick
   document.world.direction = 1
End Sub
Sub BtnReverse_OnClick
   document.world.direction = -1
End Sub
Sub spinBtn_SpinDown
   document.world.speed = document.world.speed+10
End Sub
Sub spinBtn_SpinUp
   document.world.speed = document.world.speed-10
End Sub
—>
</SCRIPT>
</body>
</html>

Simple, isn't it?

Summary

I hope this article has given you a good start in understanding Java and how scripting can enhance controls. More information can be found on this Web site and on www.microsoft.com/java/ and www.microsoft.com/visualj/. So, what's next? Well, take a look at the Visual J++ applet wizard and create some applets. You can start with the samples that come with Visual J++ if you'd rather start with code and modify it. You can also find applets on the Web and view their source code to see how they were created. Finally, try scripting an applet in Internet Explorer. Before long, you'll be a control-and-scripting machine and you, like other Webmasters, can charge obscene amounts of money for your work.