Published: December 24, 2001
By Richard G. Baldwin
Java Programming, Lecture Notes # 1602
The first lesson in the group was entitled The Essence of OOP using Java, Objects and Encapsulation.
Essence
My dictionary provides several definitions for the word essence. Among those definitions are the following:
I will attempt to provide that information in a high-level format, devoid of any requirement to understand detailed Java syntax. In those cases where an understanding of Java syntax is required, I will attempt to provide the necessary syntax information in the form of sidebars or other obvious formats.
Therefore, if you have a general understanding of computer programming, you should be able to read and understand the lessons in this miniseries, even if you don't have a strong background in the Java programming language.
Viewing tip
You may find it useful to open another copy of this lesson in a separate browser window. That will make it easier for you to scroll back and forth among the different listings while you are reading about them.
Supplementary material
I recommend that you also study the other lessons in my extensive collection of online Java tutorials. You will find those lessons published at Gamelan.com. However, as of the date of this writing, Gamelan doesn't maintain a consolidated index of my Java tutorial lessons, and sometimes they are difficult to locate there. You will find a consolidated index at Baldwin's Java Programming Tutorials.
A simple Java program will be discussed to illustrate the definition and use of two different classes. Taken in combination, these two classes simulate the manufacture and use of the car radio object discussed in an earlier lesson.
You will see how to write code to create a new Radio object by applying the new operator to the class named Radio. You will also see how to save that object's reference in a reference variable of type Radio.
You will see how to write code that is used to simulate the association of a radio button with a particular radio station.
You will see how to write code that is used to simulate the pressing of a radio button to play the radio station associated with that button.
You will see the definition of a class named Radio01. This class consists simply of the main method. The main method of a Java application is executed by the Java Virtual Machine when the application is run. Thus, it is the driver for the entire application.
You will see the definition of a class named Radio. This class includes one instance variable and two instance methods. (The instance variable is a reference variable that refers to a special kind of object that I refer to as an array object. I will provide a very brief discussion on array objects in this lesson. I will have more to say about array objects in a subsequent lesson.)
I will provide a short discussion of class variables, which are not used in this program. I will explain that the use of class variables can often lead to the undesirable side effects.
Finally, I will provide a very brief discussion of the syntax of a simple class definition in Java.
I explained in an earlier lesson that a class is a plan from which many objects can be created. I likened the class definition to the plans from which millions of nearly identical car radios can be produced.
A simple Java program
In order to help you to get started on the right foot, and in support of future discussions, it will be advantageous to provide and discuss a simple Java program in this lesson.
The car radio example
Harking back to an earlier lesson, Listing 9, near the end of the lesson, shows the code for a simple Java application that simulates the manufacture and use of a car radio.
Explain in fragments
As is my custom, in order to help you to focus specifically on important sections of code, I will explain the behavior of this program in fragments.
Top-level classes
This program contains two top-level class definitions. (Java also supports inner classes as opposed to top-level classes. The topic of inner classes may prove to be too complex for this miniseries. However, you will find lessons that discuss inner classes in the collection of tutorial lessons on my web site.)
The class named Radio01
One of those class definitions, named Radio01, is shown in its
entirety in Listing 1. The other class named Radio will be
discussed later.
public class Radio01{ public static void main( String[] args){ Radio myObjRef = new Radio(); myObjRef.setStationNumber(3,93.5); myObjRef.playStation(3); }//end main }//end class Radio01 Listing 1 |
The class named Radio01 consists simply of the main method. The main method of a Java application is executed by the Java Virtual Machine when the application is run. Thus, it is the driver for the entire application.
The driver class
The code in Listing 1 simulates the manufacturer of the radio and the use of the radio by the end user.
Without getting into a lot of detail regarding Java syntax, I will further subdivide and discuss this code in the following listings.
Constructing a Radio object
As discussed in a previous lesson, the code in Listing 2 applies the
new
operator to the constructor for the Radio class, causing a new object
to be created according to the plans specified in the class named Radio.
Radio myObjRef = new Radio(); Listing 2 |
Saving a reference to the Radio object
Also as discussed in a previous lesson, the code in Listing 2 declares a reference variable of type Radio and stores the new object's reference in that variable.
Programming the radio buttons
The code in Listing 3 is new to this discussion. This statement simulates the process of associating a particular radio station with a particular button.
As I explained in a previous lesson, this is accomplished for my car radio by manually tuning the radio to a desired station and then holding the radio button down until it beeps.
You have probably done something similar to this to the radio in your
car.
myObjRef.setStationNumber(3, 93.5); Listing 3 |
The statement in Listing 3 accomplishes the association of a simulated button to a simulated radio station by invoking the method named setStationNumber on the reference to the Radio object. (Recall that this sends a message to the object asking it to change its state.)
The parameters passed to the method cause radio button number 3 to be associated with the frequency 93.5 MHz. (The value 93.5 is stored in the instance variable that represents button number 3.)
Sending a message to the object
Using typical OOP jargon, the statement in Listing 3 sends a message to the Radio object, asking it to change its state according to the values passed as parameters.
Pressing a button on the radio
Finally, the code in Listing 4 invokes the method named playStation
on the Radio object, passing the integer value 3 (the button
number) as a parameter.
myObjRef.playStation(3); Listing 4 |
Another message
This code sends a message to the object asking it to perform an action.
In this case, the action requested by the message is:
This simple program doesn't actually play music. As we will see later, this causes the following message to appear on the computer screen, simulating the selection and playing of a specific radio station.
Playing the station at 93.5 Mhz
The Radio class
Listing 5 shows the class definition for the Radio class in its
entirety.
class Radio{ //This class simulates the plans from // which the radio object is created. protected double[] stationNumber = new double[5]; public void setStationNumber( int index,double freq){ stationNumber[index] = freq; }//end method setStationNumber public void playStation(int index){ System.out.println( "Playing the station at " + stationNumber[index] + " Mhz"); }//end method playStation }//end class Radio Listing 5 |
Note that the code in Listing 5 does not contain an explicit constructor. If you don't define a constructor when you define a new class, a default version of the constructor is provided on your behalf. That is the case for this simple program.
The plans for an object
The code in Listing 5 provides the plans from which an object that simulates a physical radio can be constructed.
An object instantiated (an object is an instance of a class) from the code in Listing 5 simulates a physical radio. I will subdivide this code into fragments and discuss it in the following listings.
An instance variable
In a previous lesson, I explained that we often say that an object is an instance of a class. (A physical radio is one instance of the plans used to produce it.)
The code in Listing 6 shows the declaration and initialization of what
is commonly referred to as an instance variable.
protected double[] stationNumber = new double[5]; Listing 6 |
Why call it an instance variable?
The name instance variable comes from the fact that every instance of the class (object) has one. (Every radio produced from the same set of plans has the ability to associate a frequency with each selector button on the front of the radio.)
Class variables - an aside
Note that Java also supports something called a class variable, which is different from an instance variable.
Class variables are shared among all of the objects created from a given class. Stated differently, no matter how many objects are instantiated from a class definition, they all share a single copy of each class variable.
There is no analogy to a class variable in a physical radio object. Radios are installed in different cars separated from each other by thousands of miles. Therefore, there can be no sharing of anything among different physical radio objects. (Well, that may not be entirely true. In today's technology, different radio objects could potentially share something at a common location via satellite communications, but my car radio doesn't do anything like that.)
Class variables can cause undesirable side effects
While class variables are relatively easy to use in Java, they are difficult to explain from an OOP viewpoint.
Also, it is my opinion that from a good overall design viewpoint, class variables should be used very sparingly, if at all.
Therefore, for the first several lessons, I will exclude the possibility of class variables in this series of lessons. I will explain the use of class variables in Java in a subsequent lesson.
Reference to an array object
Now, let's get back to the instance variable named stationNumber shown in Listing 6. Without getting into a lot of detail, this variable is also a reference variable, referring to an array object.
The array object encapsulates a simple one-dimensional array with five elements of type double. (Java array indexes begin with zero, so the index values for this array extend from 0 to 4 inclusive. I will also discuss array objects in more detail in a subsequent lesson.)
Persistence
The array object is where the data is stored that associates the frequency of a radio station with the simulated physical button on the front of the radio.
Each element in the array corresponds to one frequency-selector button on the front of the radio. Hence, the radio simulated by an object of the Radio class has five simulated frequency-selector buttons.
The array object exists when the code in Listing 6 has finished executing. Each element in the array has been initialized to a value of 0.0 (double-precision float value of zero).
The setStationNumber method
Listing 7 shows the setStationNumber method in its entirety
public void setStationNumber( int index,double freq){ stationNumber[index] = freq; }//end method setStationNumber Listing 7 |
Associates radio station with button
This is the method that is used to simulate the behavior of having the user associate a particular button with a particular radio station. (Recall that this is accomplished on my car radio by manually tuning the radio to a specific station and then holding the button down until it beeps. Your car radio probably operates in some similar way.)
This method receives two incoming parameters:
The code in the method stores the frequency value in an element of the array object discussed earlier. The element number is specified by the value of index shown in square brackets in the assignment expression. (This syntax is similar to storing a value in an array element in most programming languages that I am familiar with.)
Pressing a radio button to select a station
Listing 8 shows the playStation method. This is the method
that simulates the result of having the user press a button on the front
of the radio to select a particular radio station for play.
public void playStation(int index){ System.out.println( "Playing the station at " + stationNumber[index] + " Mhz"); }//end method playStation Listing 8 |
Selecting and playing a radio station
The method receives an integer index value as an incoming parameter. This index corresponds to the number of the button pressed by the user.
This method simulates the playing of the radio station by extracting the appropriate frequency value from the array object and displaying that value on the computer screen along with some surrounding text.
When invoked by code in the main method of this program, this method produces the following message on the computer screen:
Playing the station at 93.5 Mhz
That pretty-well summarizes the behavior of this simple program.
Class definition syntax
There are a number of items that can appear in a class definition, including the following:
In order to make these lessons as easy to understand as possible, the first several lessons will ignore the possibility of class variables, class methods, static initializer blocks, and inner classes.
As mentioned in the earlier discussion of class variables, these elements aren't particularly difficult to use, but they create a lot of complications when attempting to explain OOP from the viewpoint of Java programming.
Therefore, the first several lessons in the series will assume that class definitions are limited to the following elements:
A constructor is used only once in the lifetime of an object. It participates in the task of creating (instantiating) and initializing the object. Following instantiation, the state and behavior of an object depends entirely on instance variables and instance methods.
Instance variables and methods
The class named Radio discussed earlier contains one instance variable named stationNumber, and two instance methods named setStationNumber and playStation.
A simple Java program was discussed to illustrate the definition and use of two different classes. Taken in combination, these two classes simulate the manufacture and use of the car radio object discussed in an earlier lesson.
You saw how to write code to create a new Radio object by applying the new operator to the class named Radio. You also saw how to save that object's reference in a reference variable of type Radio.
You saw how to write code (in an instance method named setStationNumber) used to simulate the association of a radio button with a particular radio station.
You saw how to write code (in an instance method named playStation) to simulate the pressing of a radio button to play the radio station associated with that button.
You saw the definition of the class named Radio01, which consists simply of the main method. The main method of a Java application is executed by the Java Virtual Machine when the application is run.
You saw the definition of the class named Radio. This class includes one instance variable and two instance methods. (The instance variable is a reference variable that refers to a special kind of object that I refer to as an array object. I provided a very brief discussion on array objects. I will have more to say on this topic in a subsequent lesson.)
I provided a short discussion of class variables, which are not used in this program. I explained that the use of class variables could often lead to undesirable side effects.
Finally, I provided a very brief discussion of the syntax of a simple class definition in Java.
In the next lesson, I will discuss how the definition of a class defines a new data type. I will show you how to extend an existing class. I will explain what is inherited through inheritance. I will discuss code reuse and explicit constructors.
Finally, I will illustrate all of the above in a simple program that extends the Radio class discussed in this lesson into a new class named Combo that simulates an upgraded radio containing a tape player.
/*File Radio01.java Copyright 2001, R.G.Baldwin Simulates manufacture and use of a car radio. This program produces the following output on the computer screen: Playing the station at 93.5 Mhz **************************************/ public class Radio01{ //This class simulates the // manufacturer and the human user public static void main( String[] args){ Radio myObjRef = new Radio(); myObjRef.setStationNumber(3,93.5); myObjRef.playStation(3); }//end main }//end class Radio01 //---------------------------------// class Radio{ //This class simulates the plans from // which the radio object is created. protected double[] stationNumber = new double[5]; public void setStationNumber( int index,double freq){ stationNumber[index] = freq; }//end method setStationNumber public void playStation(int index){ System.out.println( "Playing the station at " + stationNumber[index] + " Mhz"); }//end method playStation }//end class Radio Listing 9 |
Copyright 2001, Richard G. Baldwin. Reproduction in whole or in part in any form or medium without express written permission from Richard Baldwin is prohibited.
Richard has participated in numerous consulting projects involving Java, XML, or a combination of the two. He frequently provides onsite Java and/or XML training at the high-tech companies located in and around Austin, Texas. He is the author of Baldwin's Java Programming Tutorials, which has gained a worldwide following among experienced and aspiring Java programmers. He has also published articles on Java Programming in Java Pro magazine.
Richard holds an MSEE degree from Southern Methodist University and has many years of experience in the application of computer technology to real-world problems.
-end-