![]() If you have done programing in Pascal, C or Standard Basic, you will find that Java code
looks quite different. The former are procedural languages, in which code is organized in
a step-by-step description of what happens next. Object-orientated programming (OOP)
languages, such as Java are organized in terms of objects. Three main properties
Characterize an OOP programming language:
OBJECTS
Objects are things. For example a cube is an object. If you were to define a cube using
Pascal or C, you would have to disassemble the cube into its basic parts. It has height,
width, area, weight, etc. You would have to use the elements to define the cube. You now
no longer have a cube but a lot of elements that define a cube.
In OOP languages, such as Java, you do not proceed that way. The cube is thought of as
a whole. The components of the cube remain together, in their essential relationships to
one another. The object "cube" represents every cube now in existence, has ever existed
in the past or will exist in the future. This is called encapsulation.
This module will give you an overview of object-oriented programming as it applies to Java.
You will learn:
Objects and Classes
When you write a program in an object-oriented language, you do not define actual
objects. You define classes of objects, where a class is an abstract of many objects with
similar characteristics. Classes are an abstract of all the features of a specific set of
objects. For example, lets say we have a class called Tree. The Tree class describes
all the things that distinguish a tree from any other set of objects. It does not describe a
Fig tree or a Maple tree or any specific tree, but the qualities that allows us to classify them
as a tree (i.e., leaves, roots, chlorophyll, grows, etc.). The Tree class serves as an
abstract model that allows us to classify an object as a tree or not a tree. Once we have
a tree class, we can identify lots of instances of the class tree, that have different features
(i.e., tall, short, bushy, etc.) but are recognizable as a tree. See Figure 1 below.
![]() NEW TERM: A class is an abstract for a set of objects with similar features.
An apple tree is an instance of the class tree. An instance of a class is an actual object.
The term class, is the generic representation of an object, the term instance of a class is
a concrete object. An instance of a class, and an object refer to the same thing. The
terms instance and object are used interchangeably in OOP terminology. An instance of
a tree and a tree object are the same thing.
NEW TERM: An instance is specific reference to a class member. Instances
and objects are the same thing.
When you are programming in java, you probably won't have a need to create a class
called tree. However, if you want to create an interface so that a user can communicate
with your program, you might need a class called Button. This class would define the
features of your button (label, size, color, etc.), and how it operates (single click, double
click to activate it?). After you define the generic Button class, you can then easily
create instances of that button. Perhaps a specific button should be red and turn green
when clicked with the mouse. By creating the Button class, you do not have to keep
rewriting the code for each individual button. You can reuse the Button class to create
different kinds of buttons as needed throughout your program.
When you create a Java program, you construct a set of classes. Then as your program executes, instances of those classes are created and discarded as needed. It is up to you to create the appropriate set of classes to carry out the desired function of your program. However, you don't have to create the classes from scratch. The Java environment comes
with a standard set of classes (the class library) that provide the basic functions you will
need to carry out basic programming tasks. It also contains classes that provide basic math
functions, arrays, strings, and graphic functions. Quite often, the Java class libraries are
comprehensive enough so that all you have to do in your Java program is create a single
class that uses the standard class libraries.
NEW TERM: A class library is a collection of classes that can be used
repeatedly in different programs. The standard Java class libraries are
designed to accomplish most basic programming tasks.
Behavior and Attributes
Every Java class has two basic features: attributes and behavior. In this module we will
learn about attributes and behaviors as they apply to a theoretical class called
Mycomputer. A computer class might contain the following attributes with the following
values:
The Attributes of an object can also include information about its state. For example, is the
computer on or off, what program is running?
Variables, are used to define the attributes of classes. The types of variables and names
are defined in the class. Each object can have its own values for these variables. Since
each instance of a class can have different values for its variables, these variables are
usually called instance variables.
NEW TERM: An instance variable defines the attributes of an object. Instance
variables' types and names are defined in the class. However, their values are
set and changed in the object.
Instance variables can be initialized when an object is created and remain constant
throughout the life of an object, or they can change at will as the program executes.
Remember, change the value of the variable and you change the object's attributes.
Besides instance variables, there are class variables. These apply to the class itself and
to all of its instances. Class variables are stored in the class itself, unlike instance
variables which are stored in the instance (object). We will learn more about class and
instance variables in later modules.
Behavior
The behavior of a class determines how an instance of that class operates. For example,
how will it "react" if requested by another class or object to do something? How will it
"react" if its internal state changes? Behavior is the only way objects can do anything to
themselves or have anything done to them. Here are some behaviors that our theoretical
class Mycomputer might have:
Sets of Java statements that accomplish some task, are referred to as methods. Methods
define an objects behavior. Methods look and behave like functions in other languages.
However, in Java they are defined and accessible only inside a class.
NEW TERM: Methods are functions defined inside classes that operate on
instances of those classes.
Not only can methods be used to operate on an individual object, but also used between
object to communicate with one another. A class or an object can call methods in another
class or object to communicate changes in the environment or to request that object to
change its state.
There can be instance and class methods, just as there are instance and class variables.
In fact instance methods are so common, they are usually just called methods. Instance
methods apply to and operate on an instance of a class. Class methods apply and operate
on the class itself. We will have more to say about methods in following modules.
Creating a Class
We will now create a working example of the Mycomputer class. The example will show
you how instance variables and methods are defined in a class in Java. We will also create
a Java application that creates a new instance of the Myomputer class and shows its
instance variables. At this point we will not go into much detail about the actual syntax in
the example. If you feel you are not sure just what is going on, don't worry about it. we will
come back to the subject and it will become clear later on. All you really need to
understand now is the basic parts of the class definition.
Open your text editor or what ever you have been using to write your Java code. Now type
the following:
Well that's it, you have just created a class. True, it doesn't do anything at this time, but
it is a Java class in its simplest form. Now lets create some instance variables for this
class. We will crate three of them. Type these lines between the curly brackets:
Now we have created three instance variables. Two of them, make and color, can
contain string objects (a series of characters). String, with a capital S, is part of the
Java class library. The third instance variable, runningState, is a boolean variable
that refers to the whether the computer is on or off. A value, false indicates that the
computer is off. A boolean variable can only be true or false. Note that boolean is
written with a lowercase b.
NEW TERM: A boolean variable can only be true or false.
Now we will add some behavior (methods) to our class. There are many things that a
computer can do, but to keep things simple, we will just add one method. A method that
starts the computer. To do this add the following lines below the instance variables.
void startComputer()
{
if (runningState == true)
System.out.println("The computer is on line.");
else
{
runningState = true;
System.out.println("The computer is now on line.");
}
}
The runningState() method tests to see if the computer is already running
(runningState == true) and if it is, it prints a message saying so. If the computer is
not already running, it changes the state to true (starting the computer) and then prints
a message. Because the startComputer() method does not return a value, its definition
is preceded by the word void. The parentheses [()] at the end of a name indicate that it is
a method and not a variable. We will have much more to say about methods in later
modules.
The code for our program should now look like the following:
1: class Mycomputer
2: {
3: String make;
4: String color;
5: boolean runningState;
6:
7: void startComputer()
8: {
9: if (runningState == true)
10: System.out.println("The computer is on line.");
11: else
12: {
13: runningState = true;
14: System.out.println("The computer is on now line.");
15: }
16: }
17: }
Before we compile our class we will add one more method between lines 16 and 17. The
method we will add is showAtts(). The showAtts() method is used to print the current
values of all the instance variables in an instance of our Mycomputer class. Type the
following:
void showAtts()
{
System.out.println("This computer is a "
+ color + " " + make);
if (runningState == true)
System.out.println("The computer is on.");
else System.out.println("The computer is off.");
}
The showAtts() method prints two lines on the screen, the make and color of the
computer object and indicates if the computer is on or off.
We now have a Java class with three instance variables and two methods defined. Save
the file and compile it.
javac Mycomputer.java
When we execute the program Mycomputer.class using java we will get an error
message. The reason is, Java assumes that the class is an application and looks for a
main() method inside the class. We don't have one. To make the Mycomputer class
functional, we have to either make it an applet or an application that contains a main()
method. We will add a main() method to our source code. We will add it just before the
last closing brace (}).
Type the following (not the line numbers):
1: public static void main (String args[])
2: {
3: Mycomputer m = new Mycomputer();
4: m.make = "Compaq 4504";
5: m.color = "Beige";
6: System.out.println("Calling showAtts...");
7: m.showAtts();
8: System.out.println("------");
9: System.out.println("Starting computer...");
10: m.startComputer();
11: System.out.println("------");
12: System.out.println("Calling showAtts...");
13: m.showAtts();
14: System.out.println("------");
15: System.out.println("Starting computer...");
16: m.startComputer();
17: }
With the main() method added, we have an official Java program. We can now compile
it and run it. This time there should be no errors. The source code should look like the
following:
class Mycomputer
{
String make;
String color;
boolean runningState;
void startComputer()
{
if (runningState == true)
System.out.println("The computer is on line.");
else
{
runningState = true;
System.out.println("The computer is on now line.");
}
}
void showAtts()
{
System.out.println("This computer is a "
+ color + " " + make);
if (runningState == true)
System.out.println("The computer is on.");
else System.out.println("The computer is off.");
}
public static void main (String args[])
{
Mycomputer m = new Mycomputer();
m.make = "Compaq 4504";
m.color = "Beige";
System.out.println("Calling showAtts...");
m.showAtts();
System.out.println("------");
System.out.println("Starting computer...");
m.startComputer();
System.out.println("------");
System.out.println("Calling showAtts...");
m.showAtts();
System.out.println("------");
System.out.println("Starting computer...");
m.startComputer();
}
}
The output of our program should look like this:
The contents of the main() method will probably look confusing to you so we will go
through it line by line to give you a basic idea of what it does. You will get more specific
details in the next two modules.
Line 1 declares the main() method. The first line of the main() method will always look
like this. Later you will learn the specifics of each part.
Line 3, Mycomputer m = new Mycomputer();, creates a new instance of the Mycomputer
class and stores a reference to it in the variable m. You do not as a rule, operate directly
on classes in Java, but you create objects from those classes and then call methods in
those objects.
Lines 4 and 5 set the instance variables for this Mycomputer object. The make is now a
Compaq 4504 and the color is beige.
Line 6 prints a message informing us that method showAtts() is about to be called.
Line 7 calls the showAtts() method. The new Mycomputer object then prints the values
of its instance variables, make and color and indicates that the computer is off.
Line 8 prints a dividing line for cosmetic effects.
Line 10 calls the startComputer() method in the Mycomputer object to start the
computer. The computer is now on.
Line 12 reprints the instance variables. This time it should indicate that the computer is on.
Line 16 attempts to start the computer, but because it is already on the message prints, The
computer is already on.
Inheritance, Interfaces and Packages
Hopefully, you now have some basic understanding of classes, objects, methods, variables,
and how to use them in a Java program. So now we will see if we can confuse you some
more. We will introduce you to inheritance, interfaces and packages which are
mechanisms used to organize classes and class behaviors. The Java class libraries use
these concepts, and the classes you write should also use these concepts.
Inheritance
Inheritance is one of the most important concepts in object-oriented programming. It effects
the way you structure and write your Java classes. It is a powerful concept that allows you
to specify how a class is different from some other class, and gives you automatic access
to the information contained in that other class. Classes are arranged in a strict hierarchy,
see Figure 3 below:
Each class has a superclass, the one above it in the hierarchy. Each class can also have
one or more subclasses, the ones below it in the hierarchy. Classes further down the
hierarchy can inherit from classes further up the hierarchy.
Subclasses inherit all the methods and variables from their superclasses. This means, if
a superclass defines behavior your class needs, you don't have to redefine it or copy that
code from some other class. Your class automatically gets that behavior from its
superclass.
NEW TERM: Object-oriented programming is the process of building family
trees for data structures in a way that data types inherit characteristics from
simpler, more general types. This mechanism is inheritance.
At the very top of the Java class hierarchy is the class Object. All classes inherit from
this one superclass. Object is the most abstract class in the hierarchy. It defines
behavior inherited by all the classes in Java. Classes further down the hierarchy add more
details and are more customized to a specific purpose.
Usually when you write a new Java class, you will want to create a class that has all the
characteristics some other class has, plus some additional information. For example, you
may a version of a Button that has some unique quality. To obtain all the Button
characteristics, all you need to do is define your class to inherit from Button. Your new
class will then automatically get all the behavior defined in Button and its superclasses.
Now all you need to do is add the things that make your class different from Button itself.
This procedure for defining new classes as the differences between them and their
superclasses is called subclassing.
Subclassing consists of creating a new class that inherits from some other class in the class
hierarchy. Therefore, all you need to do is define the differences between your class and
its parent. The rest of the characteristics are available to your class through inheritance.
NEW TERM: Subclassing is the process of creating a new class that inherits
from a preexisting class.
If you should define a class that consists of entirely new behavior, and is not really a
subclass of an other class, it will still inherit from Object. If a class definition does not
indicate its superclass in the first line of code, it by default inherits from Object. Our
Mycomputer class inherited from Object.
Creating a Class Hierarchy
We will use a bug analogy to demonstrate the value of creating superclasses and
subclasses. Suppose we created a class called Fly which works just fine. It does
everything we want it to do. Now we want to create a class called Butterfly. Flies and
Butterflies have many common characteristics. We could open the Fly class and copy
the information from that class to our new class Butterfly and add some additional
details. However, a better plan would be to factor out the common characteristics of Fly
and Butterfly and put them into a more general class. Then if we should add a class
Moth, most of the work would have been done for us. Having reusable common behavior
in a superclass reduces the amount of work we have to do over all. See Figure 5.
Once a characteristic has been defined, all categories beneath that definition include that
characteristic. Once you have identified an insect as a member of the order Fly, you don't
have to add that a fly has one pair of wings. It inherits that characteristic from its
superclass Winged. See Figure 5.
Figure 6 is another illustration of the same principle using a computer chip.
How Inheritance Works
Why can an instance of one class automatically get variables and methods from classes
further up the hierarchy? When you create a new instance of a class, there is a location
for each variable defined in the current class and for each variable defined in all its
superclasses. Therefore, all the classes combine to form a template for the current object,
and then each object fills in the appropriate information for its situation.
Method operate in a similar way. New objects have access to all the method names of its class and its superclasses. However, method definitions are called dynamically when needed. If you call a method on a specific object, Java first checks the object's class for the definition of that method. If it is not found in the object's class, it then looks in the class's superclass, and up the hierarchy until the method definition is found. See Figure 7.
Things are a little more complex when a subclass defines a method that has the same
identity (name, number, and type of arguments) as a method defined in a superclass. In
this situation, the method definition that is found first, starting at the bottom and working up
the hierarchy, is the one executed. This allows us to define a method in a subclass that has
the same identity as a method in a superclass. The identical method in the subclass will
in effect "hide" the superclass method. This is called overriding a method. We will have
more to say about this in later modules.
NEW TERM: Overriding a method is done by creating a method in a subclass
that is identical to a method in a superclass. That method hides the
superclass's method. See Figure 8.
![]() Introduction to Interfaces and Packages
Packages and interfaces are both advanced topics that will be discussed in detail in later
modules. However, we will introduce them here.
Each Java class is restricted to only one superclass, unlike most other object-oriented
programming languages, such as C++. This was done to simplify the inheritance process.
While it makes the relationship between classes easier to understand and to design, it can
be somewhat restrictive when you have similar behavior that needs to be duplicated across
different "branches" of the class hierarchy. Java gets around this problem of shared
behavior by using the concept of interfaces. Interfaces are a collection of method names
kept in one location which allow you to add those methods as a group to the various
classes that need them. Interfaces contain only method names and arguments, not actual
definitions.
Although a single Java class can only have one superclass, that class can implement any
number of interfaces. By implementing an interface, a class provides method definitions
for the method names defined by the interface. If two dissimilar classes implement the
same interface, they can both respond to the same method calls, as defined by the
interface, although what each class does in response to those method calls may be very
different.
NEW TERM: An interface is a collection of method names, that can be added
to classes to provide additional behavior not included in those methods the
class defined or inherited from its superclass. Note that interfaces do not
contain actual definitions, only names of definitions.
This is all you need to know about interfaces for now, so if you are a little confused as to
what they do don't worry. You will learn more later about interfaces.
The last new concept we will cover in this module is packages. Packages are a way of
grouping related classes and interfaces into a single library or collection. Packages allow
modular groups of classes to be available only if they are needed, there by eliminating
potential conflicts between class names in different groups of classes. You will learn all
about packages in later modules, but for now, you should know the following:
Creating a Subclass
We will now create a class that is a subclass of another class and override some methods.
We will create an applet. All applets are subclasses of the class Applet. Applet is a part
of the java.applet package. When you create a subclass of Applet you automatically
get all the behavior from the window toolkit and layout classes that enables your applet to
be located correctly on the page, and to interact with system operations (i.e., keypresses
and mouseclicks).
We will make a variation of our Hello World program from module one. Start your text
editor and type the following class definition:
public class HelloAgainApplet extends java.applet.Applet
{
}
What you have done is create a class called HelloAgainApplet. The code that says
extends java.applet.Applet, is the part that says your applet class is a subclass of
the Applet class. Because the Applet class is contained in the java.applet package,
you do not have automatic access to that class. You must explicitly refer to it by package
and class name.
The remaining part of your class definition, public is a keyword that you will learn more about in latter module. It means that your class is available to the Java system at large once it is loaded. Usually you only need to make a class public if you want it to be visible to all other classes in your Java program. Applets must be declared to be public.
So far we have created a subclass that is the same as its superclass. There is not much
point to this, so let make out subclass different by putting information between the two
braces. Lets add an instance variable to contain a Font object.
The instance variable, f, now contains a new instance of the class Font, which is part of
the java.awt package. This Font object is an Arial font, boaldface, 36 points in height.
In our pervious Hello World applet, we used the default font (12 point Times Roman). By
using a Font object, you can change the font of the text you draw in your applet. By
creating an instance variable to contain this font object, it is made available to all the
methods in your class.
When you write applets, there are several standard methods defined in the applet
superclasses that you will want to override in your applet class. They include methods to
initialize the applet, to start it running, to handle operations such as mouse movements and
clicks, etc. One of these standard methods is the paint() method. Paint() actually
displays your applet on the screen. The default definition of paint() does nothing. By
overriding paint() you tell the applet what to draw on the screen. Add the following to
your applet:
Note that this method is declared public. The reason it is declared public is because
the method it is overriding is public. If a superclass's method is defined as public, then
your override method must be public. If you don't observe this rule, at compile time, you
will get an error message.
Also note that the paint() method only accepts one argument per instance of the
Graphics class. You will more about the Graphics class in later modules.
Inside the paint() method we have done three things:
This is what our applet looks like at this point:
There is one more thing we need to do before we try to compile our applet. We make
reference to the classes Graphics and Font, which are part of a package that is not
available to us by default. The only package we have access to automatically is
java.lang. We referred to the Applet class in the first line of the class definition by
referring to its full package name, java.applet.Applet. Latter in the program we refer
to all kinds of other class as though they were available. They are not, and if we try to
compile our applet as it stands, the compiler will tell us so in the form of error messages.
We can resolve this problem by importing the classes we need. There are three of them:
Graphics, Font and Color. Add these three lines at the top of our source code, in
order to import these classes.
Note: We could have imported all the classes in the java.awt package by placing an
asterisk (*) in place of a specific class name. The asterisk means "any file whose name
begins with java.awt." This means we could replace the first three line of our source
code with one line: import java.awt*;
Below is the finial version of HelloAgainApplet.java. Compile it to obtain the file
HelloAgainApplet.class.
Now we need to create an HTML program containing the <APPLET> tag to test our applet. Type the following:
Save the above as HelloAgainApplet.html. Start your Java enabled browser and run
the new HTML program. You should see something like Figure 9.
![]() Summary
If you are not familiar with Java programming, this module probably seems overwhelming.
Don't worry about it, the more you progress in this course, and the more Java classes and
applications you write the easier it is to understand. The most difficult thing to learn in
object-oriented programming is not the concepts, but their names.
Below is a glossary of terms and concepts you have learned in this module:
class: The definition of an object.
class method: A method defined in a class, which operates on the class itself and can be
called by way of the class or any of its instances.
class variable: A variable owned by the class and all its instances. It is stored in the class.
instance: The same thing as an object. An object is an instance of some class.
instance method: A method defined in a class which operates on an instance of that class.
instant variable: A variable owned by an individual instance and whose value is stored in
the instance.
interface: A collection of abstract behavior specifications that individual class can
implement.
object: A specific instance of some class that contains both data and code.
package: A group of related Java classes. Classes other than java.lang must be
explicitly imported or referred to by full package name.
subclass: A class lower in the inheritance hierarchy than it parent.
superclass: A class higher up the inheritance hierarchy than its child. |