Objects
Objective #1: 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.
- A class 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.
- 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
- 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. The principle of hiding object data (i.e. properties)
by making them private and impossible to directly access in a client program
is called information hiding. A client programmer doesn't even know how data is stored in a class due to the choice of private properties. The term encapsulation is
used to describe the technique of hiding information in this way. The difference between information hiding and encapsulation is very subtle. For the purposes of this course, the two terms refer to
the same idea. 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.
- View this great tutorial on how to write a class: http://nhsweb.calvertnet.k12.md.us/Stroh/JAVA/FlashTut
- What is computer software? Here is an interesting view - http://www.csteachlearn.com/secret_life.html
Objective #2: Be able to write a whole class.
- Here is a class with nothing inside of it
public class Bug
{
}
- However, a class should have the following parts
public class Bug
{
default constructor
"other" constructors
accessor methods
modifier methods
"interesting" methods
properties
}
Objective #2: Be able to access and modify the properties
of an object.
- Properties of a class are also known as
attributes, instance
fields or just fields. Properties have
the scope of the entire object.
Here is an example of a class that only has three property declaration statements that declare three properties.
public class Bug
{
private int myAge;
private int myX;
private int myY;
}
Properties should be private rather than public at least according to the College Board AP exam curriculum. You need to specify a data type (e.g. int, double, or String usually) for each property. In the example above all three properties have the data type int. It is legal to initialize properties to the value zero in the property declaration statements as in
private int myAge = 0;
but the AP exam doesn't encourage this.
Properties are sometimes named with the prefix my as in the example above. This is not a requirement though but I encourage it.
- Each object that is instantiated in a 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, an error will occur.
- 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;
}
}
- 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.
Objective #3: 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 the old, original versions of 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);
- You can call a constructor after an object has already been instantiated by using the new operator.
Tank tankA = new Tank(40); // instantiating tankA with an "other" constructor & setting myAmmo to 40
System.out.println(tankA.getAmmo()); // 40
tankA.setAmmo(20);
System.out.println(tankA.getAmmo()); // 20
tankA = new Tank(10); // re-instantiating tankA wipes out previous myAmmo & sets myAmmo to 10
System.out.println(tankA.getAmmo()); // 10
It would cause an error though to re-declare an object variable as a Tank when you are re-instantiating it a second time with the new operator as in:
Tank tankA = new Tank(40); // instantiating tankA with an "other" constructor & setting myAmmo to 40
System.out.println(tankA.getAmmo()); // 40
Tank tankA = new Tank(10); // illegal to redeclare tankA as a Tank
- You can break aliasing between two object variables by setting one equal to null or by re-instantiating one by calling a constructor with the new operator.
Tank tankA = new Tank(40);
Tank tankB = tankA; // tankA & tankB are aliased & both have myAmmo properties equal to 40
tankA = null; // they are no longer aliased and there is no object (or myAmmo property) associated with tankA
System.out.println(tankB.getAmmo()); // 40
System.out.println(tankA.getAmmo()); // null exception error since tankA does not exist as an object
or
Tank tankA = new Tank(40);
Tank tankB = tankA; // tankA & tankB are aliased & both have myAmmo properties equal to 40
tankA = new Tank(20); // they are no longer aliased
System.out.println(tankB.getAmmo()); // 40
System.out.println(tankA.getAmmo()); // 20
Objective #4: Explain how object references are copied & be able to draw a supporting diagram that traces their values.