JHDL 0.3.45

| JHDL Doc Home Page | Getting Started Page | Java Basics |


Java & Object-Oriented Programming Basics

Java is an object-oriented programming language. Objects are useful for representing just about anything imaginable. JHDL uses Java objects to represent circuits, including gates, wires, registers, etc. A particular object may have fields and methods associated with it. The fields of an object are the characteristics of the object. Non-constant (non-final) fields may be modified either directly from a reference to the object, or from a method. (Access restrictions on fields and methods may limit their accessibility to certain external classes.) Java objects are described by a Java class file. When a class is instanced, the constructor of the class is executed to initialize the object, including the values of its fields.

The following code gives an example of what code for a Java class may look like:

      public class Person {
           private String name;
           public Person(String name) {
                this.name = name;
           }
           public String getName() {
                return name;
           }
           public void setName(String newName) {
                name = newName;
           }
      }

This class has one field (name), a constructor, and two methods. The methods in this class are for accessing or setting the value of the field.

One powerful capability of Java and other object-oriented programming languages is inheritance. Classes may extend other classes to inherit the capabilities of the parent class and extend the features of the class with extra or modified fields and methods. The following class extends our Person class to add extra information and capabilities.

      public class TaskPerson extends Person {
           private String taskType;
           public TaskPerson(String name, String taskType) {
                super(name);
                this.taskType = taskType;
           }
           public String getTaskType() {
                return taskType;
           }
           public void setTaskType(String newType) {
                taskType = newType;
           }
      }

This class does not specify anything having to do with the name field of the class. But because it extends the Person class, it inherits that field as well as the methods used to access it. Notice that the first line of the constructor for TaskPerson calls the constructor of the super class with the appropriate name parameter.

Now let's create a third class. This class will also extend Person.

      public class RolePerson extends Person {
           private String roleType;
           public RolePerson(String name, String roleType) {
                super(name);
                this.roleType = roleType;
           }
           public String getName() {
                return "RolePerson Name --> "+super.getName();
           }
           public String getRoleType() {
                return roleType;
           }
           public void setRoleType(String newRole) {
                roleType = newRole;
           }
      }

With these three classes put together, we are ready to build a simple Java program that demonstrates their use. Since everything in Java must belong to a class, we will create a fourth class that just has one method: a static main method. (If a field or method is static, it does not belong to any particular instance of the class of which it is a part.) A static main method that takes an array of String arguments and has no return value is a special method that may be used to begin execution of a Java program.

      public class PersonProgram {// demonstration Java program
           public static void main(String[] arguments) {
                Person[] people = new Person[3];
                people[0] = new Person("person0");
                people[1] = new TaskPerson("person1","person1 task");
                people[2] = new RolePerson("person2","person2 role");
                for ( int pInd = 0; pInd < people.length; ++pInd ) {
                     Person person = people[pInd];
                     System.out.println("Person #"+pInd+":");
                     System.out.println("     Name: "+person.getName());
                     if ( person instanceof TaskPerson )
                          System.out.println("     Task: "+((TaskPerson)person).getTaskType());
                     if ( person instanceof RolePerson )
                          System.out.println("     Role: "+((RolePerson)person).getRoleType());
                }
           }
      }

This program creates an array of Person objects and fills in the array with instances of various types of Person objects. Then a simple for loop is used to examine each of the elements of the array. Various information extracted from the Person objects is printed to the standard output stream of the system. (If this program is executed from a command line terminal or command prompt, the information is simple displayed in the same command line window.) First the getName() method is used to obtain and print the name of each Person. This works the same for all types of Person objects. Then, if the current Person object is also a TaskPerson object, its task type is obtained through the getTaskType() method and printed. This only works for the Person object in position 1, since that is the only TaskPerson object. The getTaskType() method can only be called from an instance of the TaskPerson class. But the people array in this program is not an array of TaskPerson, it is an array of Person. Therefore, if we come across an instance of TaskPerson, we must first make the program treat the instance as a TaskPerson instead of just a Person. This is called casting. To cast an object as an instance of another object, you just put the name of the desired object type in parentheses just before the object variable in your code. This allows us to temporarily treat the second entry in the array as a TaskPerson so that we can find out its task type. Be careful with casting, though. If you cast an object to a type that it actually isn't, then Java will generate a ClassCastException, which will cause your program to halt unless it is specifically trapped. The last part of our example program displays the role type of the Person if it is an instance of RolePerson.

This program demonstrates simple inheritance. Also demonstrated here is another powerful object-oriented concept known as polymorphism. Polymorphism is similar to inheritance, but has a special twist. It is shown here with the getName() method of the RolePerson class. The RolePerson class would normally inherit that method from its super class, but instead it reimplements it so that if that method is called on an instance of RolePerson, specialized behavior for that class is exhibited instead. This is known as method overriding. In our example program, we have an array of Person. Even though the call to the getName() method is done on an object that is treated like a Person object (instead of a TaskPerson or RolePerson object) the special getName() method of the RolePerson class is invoked if the object happens to be an instance of that class. The output of this program looks like the following:

     Person #0:
          Name: person0
     Person #1:
          Name: person1
          Task: person1 task
     Person #2:
          Name: RolePerson Name --> person2
          Role: person2 role
      

Compiling & Running Java Programs

All Java source code must be contained in files with the .java extenstion. Each Java file typically contains the code for a single class, and may contain, at most, the code for just one public class. (Public means that the class is visible to other classes that aren't in the same package. Java packages are means of grouping classes in meaningful ways; e.g. the java.io package is a collection of classes that used for input and output, such as FileInputStream.)

Java files must be compiled to class files before the Java virtual machine (JVM) can interpret and execute the code. The Java Software Development Kit (SDK) includes a Java compiler, called javac. To use the Java compiler, just execute it from a command line, giving it the names of the files you want to compile. To compile the Java source code for the above example you would execute the following:

     javac Person.java TaskPerson.java RolePerson.java PersonProgram.java

This will generate the files Person.class, TaskPerson.class, RolePerson.class, and PersonProgram.class. Sometimes Java files require functionality from classes that are in other packages or locations in your file system. This usually means that you must tell javac where those files are located by setting you CLASSPATH environment variable.

Once you have the class files generated, you are ready to execute the Java program. Not all class files may be executed by the JVM though. Only class files that contain a static main method (of the form public static void main(String[] arguments)) may be executed. Use the java (included with the Java SDK) command to execute such a class. Our Person classes example may be executed as follows:

     java PersonProgram

The java program will also need to know the location of classes in other packages and locations if they are required by classes that run in the Java program you have written. This also requires that the CLASSPATH be set.

Getting Started

Now you can get started with your own Java programming. Start by downloading and installing the Java J2SE SDK from Sun Microsystems. Try saving the following files to your system and compiling and executing them.

Person.java
TaskPerson.java
RolePerson.java
PersonProgram.java

[email protected]
Last modified: Wed Jul 03 09:43:59 MDT 2002