Wyo Java Ch. 2 Lecture Notes
Objective #1: Explain the differences between an object, an object variable, and an object reference.
- Objects are used
in Java to store data. In fact, one object can store multiple pieces of
data which
are called properties (aka instance fields or just fields). For example,
a Rectangle object
might store its width and height as properties. A Circle object might store
its
radius
as
a property.
A Person object might store its name, age, and height as properties.
- In old-fashioned computer programming languages such as FORTRAN, COBOL,
C, and BASIC, objects were not used to store data. Instead, variables and
inefficient combinations of variables were used to store data. We will later
learn how variables can be used in Java, however objects are much more
efficient and powerful when it comes to storing data.
- An object must be associated with a specific type (aka data type). For
example, an object could be a Rectangle object or an object could be an Circle object but not both at the same time.
Objects
of different types require different amounts of memory to store their data
and of course have different types of objects have different sets of properties.
- If you want to use an object to store data, it is usually necessary
to first declare an object variable and then attach the object variable to
the object. An object variable is essentially a variable that stores the
object reference (i.e. memory address) of an actual object. An object reference
is really a fancy name for the memory address of an object in the memory
(i.e. RAM) of the computer. Object references are often referred to as hexadecimal
(base 16) numbers and represented as numbers that begin with 0x. Actually,
at the lowest level of the computer, an object reference is simply a binary
number made up of 1's and 0's, but it is easier for computer programmers
to specifically refer to a memory address by translating its binary number
into a hexadecimal number since hex numbers are much shorter to write.
- A Rectangle object itself
might consume a lot of space, maybe 30000 bytes (i.e. 30 kb) of memory. But
an object variable named myBox might only use
8 bytes of memory to store the object reference (i.e. memory address) of
where
the
actual
Rectangle object is stored in the memory of the computer. For technical reasons, a
computer's operating system must know where all pieces of data are stored
at all times in order for computer programs to work correctly.
- The following statement would be used at the beginning of a Java program
to declare an object variable named myBox that is capable of storing the
memory address for a Rectangle object. This statement is a declaration
statement since it declares an object variable. We call this "declaring a reference".
Rectangle myBox;
Notice that the type of the object variable (Rectangle) is typed first followed
by the object variable name. The object variable is made up by the programmer
and must begin with a letter. It cannot
contain
spaces or
most
symbols
such as
$, #, %, *, etc. In fact, you generally must follow the same rules for
object variable names that you use for naming plain variables in programming
languages
like Visual Basic.
- When you attach the object variable myBox to an actual Rectangle object
it's called instantiating an object. It's also referred to as constructing
an object. The following statement instantiates an actual Rectangle object
and attaches the object to the object variable myBox.
myBox = new Rectangle();
The new operator is used to tell Java to create the actual Rectangle object
in 30000 available bytes of memory and refer to that area of memory as myBox for the rest of the computer program. The empty parentheses are required because
the statement is actually invoking something called a constructor that acts
like a method in Visual Basic.
- The two statements
Rectangle myBox;
myBox = new Rectangle();
could be combined into the single statement
Rectangle myBox = new Rectangle();
- You must be careful to always remember to declare an object
variable AND instantiate an actual object before attempting to use an object's
methods. The following code segment does not work correctly since a Tank object was never instantiated therefore it is impossible to move the Tank
if it doesn't exist.
Tank tankA;
tankA.move(5, 6);
- Here is an analogy
that may help you understand the relationship between an object,
an object
variable,
and
an
object reference.
Think
of
the house
that you
live in as an object. It is a rather large chunk of memory that stores
multiple pieces of data (i.e. your family members). Think of your mailing
address
(e.g. 123 Reading Boulevard) as an object reference. Your local post office
(like the operating system of the computer) needs to know where your house
is located (i.e. stored) in order to provide mail service. Pretend that
your parents put up a nicely painted sign in your front lawn with a cute
name
for you house, say The Smith Plantation. In this case, the name "The
Smith Plantation" is like an object variable that is used to store
your mailing address of
123 Reading Boulevard, which in turn helps other people find your actual
house.
- Two object variables may contain the same object reference and therefore
refer to the same object in the memory of the computer. In the following
example
Tank tankA = new Tank();
Tank tankB = tankA;
tankA.setAmmo(30);
both object variables tankA and tankB contain
the object reference. Furthermore, setting tankA's
ammo to 30 also sets tankB's
ammo to 30 since they really are the same object. Using the analogy above
this is kind of
like having
two names for your home, "The Smith Plantation" and "Happy
Meadow Farm". This technique of setting one object variable equal to
the reference of another object variable is called aliasing, which is generally
discouraged especially for beginner programmers.
- In the following example however, the two object
variables are NOT the same object since they do not contain the same object
reference
Tank tankA = new Tank(40);
Tank tankB = new Tank(40);
Objective #2: Use constructors.
- A constructor is a block of code that
is executed when an object is instantiated (i.e. constructed). A constructor
usually initializes a
newly
instantiated object by setting initial values to the object's properties
(i.e. fields).
- The statement
myBox = new Rectangle();
causes the Java compiler to execute the default constructor of the Rectangle class since the ...Rectangle()... portion of that statement refers to what
is called the default constructor of the Rectangle class. There can only be
one default constructor in a class. The default constructor is called when
the parentheses are left empty. A default constructor usually sets all of
the properties of an object to 0.
- A class, by the
way, is simply a template or definition that
contains the list of constructors, methods, and properties that can be used
with an object. The name of an object's class is always the exact same as
the word
that indicates the type of an object variable in an object variable's declaration
statement.
- The following statement serves as another example of using a constructor
in the Rectangle class other than its default constructor:
myBox = new Rectangle(20, 30);
The 2 parameters in the parentheses represent the width and height, respectively.
This constructor is being used to give the Rectangle object "interesting" dimensions
rather than a width and height of zero as happened in the case of using the
default constructor above.
- A default
constructor is a constructor that accepts no parameters.
- A class may have many constructors
but only one default constructor. I call these "other constructors".
Other constructors accept one or more parameters. Each of the "other" constructors
must have a
different parameter list (aka signature). Either the number of parameters between two other constructors must be different
or
the order
of the data
types
of
the parameters
must be different. Including many other constructors in a class makes it
easier for client programmers to instantiate objects of the class.
- If no constructors are included in a class, the Java compiler will automatically
supply a default constructor. However, if at least one other constructor
is specified then the compiler WILL NOT include an automatic default constructor.
- One constructor can call another constructor for efficiency. If you have
an other constructor that accepts the parameters ammo, x, and
y such as
public Tank(int ammo, int x, int y)
{
myAmmo = ammo;
myX = x;
myY = y;
}
then you can implement the Tank class's default constructor in this way....
public Tank()
{
this(10, 0, 0);
}
where the this keyword is used as a call statement that passes
3 values to the other constructor which accepts three int parameters.
- A constructor must have the exact same
name as the class to which it belongs.
- A parameter to a constructor or a method is
called an explicit parameter. The object (i.e. instance) itself that is
being manipulated by a method or constructor is referred to as the implicit
parameter.
An implicit parameter can be referred to through the this keyword.
- An explicit parameter is also known as a formal
parameter if it is located in the method where it is being passed to. An explicit parameter
is known as an actual parameter or argument where it is being used in the
call statement that passes it to the called method.
- Technically, constructors are not considered to be methods.
- String objects are exceptions
to the rule of using the new operator or even constructors in general. Either
of the statements below can be used to declare a String object variable,
instantiate
an actual
String object, and immediately initialize it to the word "Smith"
String lastName = new String("Smith");
or
String lastName = "Smith";
- If no constructor is typed out in a class, Java will provide a default constructor behind the scenes. In this case, all int and double properties will be initialized to zero by default.
Objective #3: Implement a class by creating methods,
constructors, and properties within
the class.
- Most Java programs uses many classes. Each class is stored
and compiled in a separate file.
- A strength of Java is that the language is geared to allow
developers to reuse each others' classes. That is why
it
is called
an object-oriented programming (OOP) language because each class defines
a different kind of object that can be used in a program. There are hundreds
or maybe even thousands
of free
Java
classes
that have already
been
developed
by Sun
Microsystems as
well as independent professional Java class developers since the early
1990's. To use these classes and to be able to declare objects from these
classes, it
may be
as simple
as
importing the class into your Java program.
- To import many of the classes that come from Sun,
you simply add an import statement at the top of your Java file. The statement
import java.awt.Rectangle;
imports the class named Rectangle that is
found in the abstract windowing toolkit (awt) package. A
package is a collection of related classes. There are many packages available
through Sun. Typing this statement at the top of a program allows you
to declare and instantiate Rectangle objects.
- In order for a class to be imported as demonstrated above,
the class must have been already implemented. Implementing
a class means to write out all
of its methods, constructors, and properties. Classes implemented by Sun
can be found in the Java API at java.sun.com/j2se/1.4.2/docs/api .
Look along the left column. The classes that you are responsible for knowing
on the AP exam can be found in the AP CS Subset API at www.minich.com/education/wyo/java/apapi/doc
- See the Ch. 2 demo programs for an example of a Tank class and a Bot class
that Mr. Minich implemented.
- The public interface of a class is simply
the list of constructors and methods that can be used to create and manipulate
objects from the class in a program developed by a client programmer.
Think
of the
Java
API as being a set of class interfaces.
- When someone hires you to develop a class, you must carefully
decide what properties (also called "data") and what methods (also
called
"behavior") an object of the class should have. For example, if
you are creating a class named Student should
you have one field named name or two separate fields named firstName and lastName?
A client programmer is a person who makes use of the class that you develop.
Programs that use objects from your class are called client programs. Should
a client programmer be able to access a Student object's socialSecurityNumber so
should you include a getSocSec accessor
method or not? This process of carefully identifying the essential features
of a class is known as abstraction and the process as a
whole is also called object-oriented design (OOD). The implementation
of a class is usually private and hidden from client programmers who wish
to use objects created from the class. Hiding object data (i.e. properties)
by making them private and impossible to directly access in a client program
is called encapsulation. Encapsulation is an important principle
in object-oriented programming. It's almost as if the person who designs
and implements a class
(i.e. a class developer) does not trust the programmer who is going to use
objects from that class in a client program (i.e. the client programmer).
The client programmer is forced to indirectly access and modify an object's
properties through the object's public methods.
- According to the principles of object-oriented design
and programming, an object has state and behavior. Its behavior is
defined by the methods that are included in its class definition. Its state is
defined by the properties that are included in its class definition.
- After you define and implement a class or even while you
are implementing a class, you should also make a separate test class to test
your newly implemented
class's methods and constructors. A test class is often
named by placing the word Test after the name of the class that you are testing.
For example,
a test class for the Rectangle class might
be named RectangleTest. A test class is
an example of a client program.
- Methods are reusable sections of code that perform actions
on or with an object. For example, the Rectangle class
has a translate method.
The translate method allows a programmer
to move the Rectangle object's x and y properties.
If you implemented a Tank class, you might
include move or shoot methods
while properties of the Tank class might
include x and y locations
as well as an ammo property.
- It is proper style to begin the name of a method and the name of a property
with a lowercase letter as in width or move. It is proper style to capitalize
the name of the class itself as in Rectangle or Tank.
- To implement an individual method within a class means
to type code into body of the method so the method knows how to perform when
it is called. The method name, parameters, and body statements together are
called the method's definition.
- Within the method of a class, you may call another method within the same
class without having to type anything in front of the dot operator. Although,
you may optionally use the keyword this.
public void moveRight()
{
myX = getX() + 10;
}
or
public void moveRight()
{
myX = this.getX() + 10;
}
However, from within a client program, you must have declared an object variable
from the class and type the method name that you are calling after the name of
that
object variable as in
public static void main(String[] args)
{
Fish nemo = new Fish(10, 20);
Fish willie = new Fish(30, 15);
System.out.println("My horizontal position is " + getX());
}
Here the method call getX() is
not legal since the compiler
doesn't know which
fish (nemo or willie)
you are talking about.
- One or more parameters may be passed to a method.
The identifiers x and y in the following move method
are explicit parameters. More specifically, they are sometimes called formal
parameters as
well since their names are simply formal placeholders that only store values
passed to them.
public void move(int x, int y)
{
myX = myX + x;
myY = myY + y;
}
A value or variable identifier that is found in the call statement that calls
a
method from a client program such as the values 20 & 30 in the following statement
is called
an actual
parameter (and sometimes called an argument).
tankA.move(20, 30);
A whole object variable may even be passed as a parameter!
The following method
public void move(Tank another)
{
myX = another.getX();
myY = another.getY();
}
could be called with the call statement
tankA.move(tankB);
where tankB is an actual parameter, another is
an explicit formal parameter and
tankA is the implicit parameter.
- It is possible to include two methods with the same
name in a class. For example, you can have one method in a Tank class
named move that
accepts no parameters and another method named move that
accepts one parameter as in the following example. These two methods are
called overloaded methods since they share the same name
but have different parameter lists (also known as method signatures). One
parameter list can be different from another by having a different number
of parameters,
having
parameters
with
different data types, or by having the same number of parameters
but with
the data
types in a different order.
public void move()
{
myX = myX + 5;
}
public void move(int amount)
{
myX = myX + amount;
}
- View this great tutorial on how to write a class: http://nhsweb.calvertnet.k12.md.us/Stroh/JAVA/FlashTut
Objective #4: Be able to access and modify properties
of an object and use local variables within the methods of a class.
- Properties of a class are also known as
attributes, instance
fields or just fields. Properties have
the scope of the entire object.
- Each object that is instantiated in a test class (i.e. client
program) has its own set of instance fields. For example, the myAmmo property
of tankA could
store a value of 10 while the myAmmo property
of tankB may contain a value
of 40.
- To access property from within a test class, you need to use type the object
variable name followed by the dot operator and then the name of the property:
System.out.println(tankA.myAmmo);
The property is myAmmo and
the object variable name is tankA.
Before you attempt to access an object's property, you must have instantiated
and initialized the object. Otherwise, a compile error will be generated.
- To access a property from within a method or a constructor of the class itself,
you only need to use the name of the property as in
myAmmo = 10;
However, you can also use the word this along with the dot operator as in
this.myAmmo = 10;
The keyword this is Java's way of referencing
the object itself that is being manipulated. In other words, the this keyword
denotes the implicit parameter. Style-wise there is no need to use this in
the example above.
- Within the methods and constructors of a class, you have
access to private properties so you can use assignment statements such as
myAmmo = 20;
even if myAmmo is a private property. However, you can still use a modifier
method to change the value of a property within another method of the class.
Either of the statements
this.setAmmo(20); or setAmmo(20);
could be
used to assign the value of 20 to the private property myAmmo from within the
class.
Note that in one of the examples above where an object variable is passed as
an explicit parameter, it is possible to manipulate the private properties
of the paramater object variable as long as the code is found within the class
itself. See this example which has no errors:
public class Bot
{
private int health;
private int ammo;
// constructors, accessors, modifiers found here
public void fight(Bot enemyBot)
{
enemyBot.health -= 10;
this.ammo -= 1;
}
}
- Constants are declared by placing
the keyword final before
the usual declaration. For example in the main method of a test class, you
might use the statement
final int PI =
3.1415926;
which declares a constant named PI that
can be used over and over again in the main method
without fear of accidentally changing the value of PI to
something else. A constant is also useful
since the name DOZEN is much easier to recognize
and reuse than typing out the number 3.1415926. Constants should be named
with all-capital letters for good style and underscores should be used to
separate multiple words as in SPEED_OF_LIGHT
Within a class such as the Tank class, a constant would be declared near
the properties of the class with the statement
private final static int MAX_AMMO = 25;
In this example, the constant is made private so that MAX_AMMO can only be
used within the Tank class. However, it is sometimes useful to use public rather than private so that the constant can be used in client programs,
test classes, and other classes. The static keyword is used so that there
is only one copy of MAX_AMMO rather than one copy per Tank object that happens
to be instantiated at a given moment. We will study more about this use of
static later.
- All properties that are not constants should
normally be declared as private rather than public or protected.
We will study
exceptions to this rule when we will declare a property as protected later
in the school year. The following statement declares a property within a class
private int ammo;
Unlike constants, you should not initialize a property to a given value such
as zero in its declaration statement. That is do not use the statement
private int ammo = 0;
In our AP course, we will use constructors to initialize the values of properties.
- Local variables can be declared and used
within individual methods in a class as in this move method from our example
Tank class:
public void shoot()
{
int num = 0;
num = myAmmo - 1;
myAmmo = num;
}
Clearly though the use of the local variable num is a waste in this example
since the single statement myAmmo--; would
have sufficed.
Local variables are similar to variables
in programming languages like Visual Basic. A local variable can store a numeric
variable. Technically there is no string primitive data type in Java. More
about that later. An int variable
can store whole numbers while a double variable
can store floating-point values (i.e. decimal numbers). A boolean variable
can store either true or false. We will learn more about variables and data
types in the next chapter. In addition to int and double local variables, you
can also declare and instantiate an object as a local variable though this
will rarely need to be done for most of our programming exercises in this course.
But here is an example anyway:
public void shoot()
{
Tank tankTemp = new Tank();
tankTemp.move(30, 50);
myX = tankTemp.myX;
myY = tankTemp.myY;
}
The object variable tankTemp is local to the method shoot. Furthermore, it is
legal to use an object in the implementation of one of its own methods! It is
also legal to reference tankTemp's private myX property since this code is found
within the class itself. However, using an accessor as in myX
= tankTemp.getX(); is legal as well.
- A local variable MUST be initialized when it is declared inside of a method.
For example, the method
public void reload(int amount)
{
int sum;
sum = amount + myAmmo;
myAmmo = sum;
}
will cause a compile error since sum was not
initialized. Unlike Visual Basic, Java does not automatically initialize local
variables to zero.
- A local variable only has a scope of the method in
which it is declared. That is, you cannot refer to a local variable in another
method. Once the method
has executed and when the compiler reaches the method's closing curly brace,
all of the method's local variables are discarded and "garbage collected".
Garbage collection is an aspect of Java in which the memory occupied by unused
variables is constantly being reclaimed as a program executes.
- To access a local variable within the method where it is
declared, you simply refer to the name of the local variable. You do not attach
the local variable name to an object variable name. For example, the statement
System.out.println(num);
correctly accesses the local variable num (assuming
that num is declared in the method where this
statement appears).
- Be careful not create a side effect when writing an accessor method. One type of side effect is a logic error that modifies a property of a class in addition to returning
a property's value.
Objective #6: Document Java source code appropriately.
- Follow our class Coding
Standards for advice on documenting
Java source code.
- There are three kinds of comments in Java
- You can comment out a single line by using // as in
// this is a comment
or
System.out.println("hello world"); // this is a comment
- You can use a block comment to comment out a section of code over multiple lines as in
/*
This is ignored
by the computer
*/
Everything between the /* and the */ is treated as a comment.
- Or you can use javadoc-style comments by placing a comment between /** and */ as in
System.out.println("hello world"); /** This is ignored by the computer
even though it extends over multiple lines */
However, javadoc-style comments that begin with /** instead of /* are meant for serious comments that are used to create HTML API manuals.
- You can use javadoc-style comments to
efficiently create an online manual for your Java classes. However javadoc
documentation is
not
tested
on the AP exam and you will not be required to add javadoc comments to programming
assignments this school year.
- At the top of a class, you should include a Javadoc comment
explaining the purpose of the class. When documenting methods, you should
include a
Javadoc comment directly above the first line
of the
method.
- The
first
line
of this
comment
should
summarize the method. Then, on successive lines of the comment, you should
list the purpose of each explicit parameter (if applicable) beginning with
a @param tag. Finally, you should include
a line that explains the value that is returned (if applicable) by the
method. This line must begin with a @return tag.
- Since the javadoc utility that creates HTML Web pages
from your Javadoc comments within a class, you can include HTML tags within
your Javadoc comments.
Objective #7: Create an executable jar file that can also be used as a library class.
- A jar file can be used as an executable file. That is, by double-clicking the jar file, a Java application executes. All of the files used by a project are combined into one file.
- Follow the instructions at www.skylit.com/javamethods/faqs/createjar.html