CS 3230 - Chap 4 Notes

Objects and Classes

Object-Oriented Concepts and Design

Vocabulary Terms (p.91)

Numerous different terms are used in the context of Object-Oriented Programming, many of them refer to the same thing.

Class: A blueprint or template from which objects are made. You only write one of these.

Object: A specific example (or instance) of a class. If a class is the blueprints, an object is a house. You can have N of these.

Instantiate: Create a new object, or a new instance of a class.

Encapsulation: Wrapping variables and functions inside a class; a way to accomplish data hiding. ("Modularization" is the closest procedural programming equivalent.) The terms "abstraction", and "black box" are often bandied about, as well as "objects should have secrets".

Properties: Variables that are encapsulated in a class. Also called fields. Use these to keep track of the state of an object (more on this later).

Methods: Functions that are encapsulated in a class.

Members: Generic term used to refer to the collection of properties and methods of a class.

"OO": Object-Oriented (compared to "Procedure Oriented").

"OOP": Object-Oriented Programming (compared to "Procedural Programming").

Characteristics of Objects (p.91)

There are two ways of looking at an object, summed up in the following table.

Characteristic Design Perspective Implementor Perspective
Behavior What can I do with this object? What are the methods?
State How does the object react when you do things with it? How do the properties change when the methods are called?
Identity What distinguishes this object from other instances? What is the address of this object's reference? Also overriding any of: equals(), toString() and possibly hashCode().

Object Relationships (p.92)

Pointy-headed OO wonks will tell you that there are zillions of possible relationships between objects. Practically speaking, there are only three you need to know about:

  1. Uses: (or Dependency) Object B is passed to a method of object A.
  2. Has-a: (or Aggregation) Object A contains a property that is object B.
  3. Is-a: (or Inheritance) Object B is derived from Object A.

UML (p.93) has emerged as the model of choice for diagraming object relationships.

OO Design vs. Procedural Design (p.94)

Procedural design is function-centric: We use step-wise refinement to break a large function into numerous smaller functions creating a "tree" with a single main() function at the top and numerous terminal functions at the bottom.

OO design is data-centric: We look at a the requirements document and pick the noun phrases as our objects and think about what properties (data) they contain. Secondarily, we look at the verb phrases and make them methods of appropriate objects. There is no "top" to start from, making OO design a bit more tricky to newcomers. CRC charts ("Class Relationship Collaborations") can be used as an OO design tool.

Advantages of OOP over Procedural: (p.94 bottom - p.95 top):

Working With Existing Classes (p.96)

Using Static Members of Existing Classes (p.96)

You do not need an instance of a class to use the static methods or properties, simply use the class name followed by the member. Examples:

System.out.println("Hello world");
double rnd = Math.random();
double pi = Math.PI;
double e = Math.E;

Static members are also called class methods or class variables as opposed to instance methods or instance variables.

Making a new Instance of an Existing Class (p.96)

To make a new instance, you must call a class' constructor, which is a special method that has the same name as the class. The new operator returns a reference to the new class.

Invoking a class' constructor: (p.96) Syntax: ClassName identifier = new ClassName(args...);. You can often pass arguments to the constructor (usually for the purpose of initializing some of its properties), examples:

Date now = new Date()
Employee emp = new Employee("Raul", "Zippowitz", hireDate);

Note to C++ users: Look at p.98 for an explanation of how objects in Java are always declared from the heap, never from the stack.

Using a "factory" method: (p.96, p.116) An alternative to a constructor, you can use a method (of the same or another class) that returns a new instance. Examples:

String str = myDate.toString();
Toolkit tk = Toolkit.getDefaultToolkit();
NumberFormat currFmt = NumberFormat.getCurrencyInstance();

Note that if you use a "factory" method, you do not need to use the new operator.

And yes, this could arguably be considered a fourth object relationship: "produces".

Calling an Object's Methods

Use the field accessor operator (.) to call a method.

Accessors: (p.100) This is a five-dollar word for a "get" method; one that returns the value of a property or a computed value (which contributes to the whole "encapsulation" idea).

Mutators: (p.100) This is a five-dollar word for a "set" method; one that assigns a value to a property or changes an object's state. This also contributes to the "encapsulation" idea because values can be validated before assigning.

Passing parameters to methods: (p.118) Primitives and objects work differently here:

See ValueReference.java for an example.

Writing Your Own Classes

Declaring (p.104)

class Identifier { ...body... }. Note the format suggested at the bottom of p.104-105 and the following note on p.105. Good advice.

Constructors (p.108 bottom)

Syntax: Declare a method with the same name as your class, as many parameters as you like, and no return value (remember, it's the new operator that returns a reference).

Overloaded constructors: (p.124) You can make numerous different constructors which can construct your object in different ways by giving them different parameters. This is known as overloading and can be done for any method. Textbook definition of overloading: 2 or more methods in the same class with the same name but different signatures, which is the number, type, and order of the parameters (return value is not part of the signature).

Default constructors: (p.125) If you do not explicitly declare a constructor in your class, the compiler will make a default constructor for you which takes no arguments and has an empty method body.

Destructors (p.131)

All classes have a finalize method that can be called to destroy it (difference from C++).

In practice, destructors are not often used in Java. In C++, you need to use destructors to free allocated memory (matching calls to new with a call to delete), but in Java garbage collection takes care of that for you.

There may still be occasions where you need to perform some "teardown" work (such as closing open files, database connections, or network connections).

Methods (p.110)

Instance Methods: Write your own, give 'em parameters, write code. Calling code will need an instance of the object to call these.

Static Methods: (p.115) Simply put the keyword static in front to make the method usable without having an instance of a class. Note: static methods can only use local variables, static variables in the class (see below) and can only call other static methods; static methods cannot call instance methods.

Private Methods: (p.113) Declare a method with private to make it only callable by other methods of the class (method cannot be called outside the class). This contributes to the idea of "encapsulation" ("objects should have secrets").

Properties

Instance Variables: Same as a variable declaration done in a method, but placed inside the class body. These variables have class scope (as opposed to local scope) meaning they are visible / usable in all the methods of a class. You need an instance of a class to use an instance variable and there will be one of these declared per every instance of the class.

Initialization: (p.125) Unlike C++, you can initialize both instance variables and static variables where they are declared in the class body. You can do this instead of assigning it a value in a constructor.

Static Variables: (p.114) (or "Class Variables") Declare a variable with the static keyword to make a variable that can be used without an instance of a class. There is only one of these declared ever, no matter how many instances you create.

Constant Variables: (p.113 bottom, p.114 bottom) Declare a variable with final to make it constant. Note: if you do this you must initialize it in the declaration because you cannot assign it a value afterward. Math.PI and Math.E are examples of static, constant variables.

Private Variables: (p.142 bottom, p.113 top) As with methods, declare a variable with the private keyword to make it inaccessable outide the class. You should do this with all instance variables.

Buncha Miscellaneous Stuff

Packages (p.131)

A package is a namespace where classes can live. It is analogous to the namespace keyword in newer versions of C++ but a Java package can only hold classes (functions and variables must live inside classes). Package names like java.util and java.util.jar are not "nested" packages either; the compiler treats them as seperate packages with different names.

Importing packages: (p.132) Type import packagename.*; to bring all the classes of a package into the namespace of your current program.

If you don't do this, you will need to access the class by its fully-qualified package name, i.e. javax.swing.tree.JTree, which is kind of a pain.

The classes in the java.lang package are imported by default into every program. This contains things like the String and System classes. Full description of contents can be read in the online docs.

Declaring your own packages: (p.133 middle) You can use the package keyword followed by an identifier to make a class belong to a package. Typically, the classes in a package are put in their own directory or JAR file. (You guys did this when you made MyFirstRobot.)

Automatic Compilation of Dependencies (p.107 bottom)

If your program uses a class contained in another file, you do not have to compile it first. Just compile the file with a main method in it an the Java compiler will automatically compile all the dependant files. This is a wonderful thing.

Generating Documentation with 'javadoc' (p.139)

Any multi-line comments prefixed with /** (note the two asterisks) can be extracted with the javadoc utility and used to make HTML documentation. This is how the Java API documentation is made as well as the Robocode API.

If you're going to propperly document your code, all public interfaces (classes, methods, and properties) should have javadoc-style comments before them.

Your book explains in detail how to do this starting on p.139 and I will not repeat everything here.

The documentation on how the javadoc utility program works can be found here.

Class Design Hints (p.142 bottom)

Please read the "Class Design Hints" starting at the bottom of p.142 and on through p.144. A great deal of wisdom in a very short space.