Week 4: Objects and classes
More Object Oriented Programming ("OO")
- organization around data ("objects",
"variables"), not behavior
("methods", "functions")
- object has data and behavior
- class is definition of an object, like a "type"
- defines data
- defines methods - functions that act on the data
- many objects ("instances") are created from a
class
- String is an example of a class, "ABC"
is an example of a String object
- Vector is another example of a class, we can
create any number of Vector objects
- class is a "cookie cutter (container)", objects
are "cookies"
- encapsulation
- data and methods can be "private", i.e.
for use only within the object
- allows for changes in the future
- hides complexity from users of class
- reuse - means less code to write (If we design correctly)
!
Using existing classes
- declare a variable
- create an object from a class (using new)
- "construction"
Vector()
Vector(3)
Vector(3, 1)
- can be combined with declaration
- call methods on the object
- multiple objects of the same class can exist
- each object has its own copy of data
- multiple variables can refer to the same or different
object
- variables can set to null
- the variable does not refer to an object
- this is the default
Examples (Vector again):
// Declaration:
Vector v1;
Vector v2;
// Construction:
v1 = new Vector ();
// Combined declaration and construction:
Vector v3 = new Vector ();
// Call methods on the objects.
v1.addElement ("Hello");
int s = v2.size ();
v3.setCapacity (34);
// This does not copy the data from v3 into v2.
// Instead, it makes v2 and v3 refer to the same object.
v2 = v3;
// Set v1 to null.
v1 = null;
FYI - Some More "Complex" Data Structure
Create Your Own Classes
- class definition
- defines "member" data and methods
- order is not significant
- usually in its own source file, called ClassName.java
- compiled into its own class file, ClassName.class
Examples:
class Fraction
{
// Class data.
int numerator = 0;
int denominator = 1;
// Member methods.
double toDouble ()
{
// We need to cast the ints to doubles before
// dividing so that we do not lose the decimal part.
return (double) numerator / (double) denominator;
}
// Mult by another Fraction Object
void multiplyBy (Fraction other)
{
numerator *= other.numerator;
denominator *= other.denominator;
}
}
Constructors
- special methods for initialization
- allows class to define how it can be initialized
- always have the same name as the class
- can have 0 or more parameters
- no return value
- multiple constructors can be provided
(Vector(), Vector(int), Vector(int, int)
- default if none provided
- can only be called with "new"
Examples:
class Fraction
{
// Member data.
// ...
// Constructors.
Fraction ()
{
numerator = 0;
denominator = 1;
}
Fraction (int n, int d)
{
numerator = n;
denominator = d;
}
// Member methods.
// ...
}
Example usages:
Fraction f1 = new Fraction ();
Fraction f2 = new Fraction (4, 5);
Access Modifiers
- used to control encapsulation
(Describe who can use the method or who can use the class
if a modifier is used in the name of the class)
- every member (data and methods) can have an access
modifier
(Accessor - The implementation is transparent to the
user, so we have the ability of changing under the cover)
(Mutator - Perform error-checking, whereas code that
simply assigns to a field cannot.)
- four levels of access
- public
means that any method in any class that has
access to an instance fields/operations of the
defined class can call the method
- private
No outside agency can access the instance
fields/operations except through the methods of
the defined class
- package-scope (the default)
If do not specify public or private, then the
feature (data and methods) can be accessed by all
methods in the same package.
- protected
Subclasses have access to a method or to data
from a parent class
(Use with caution, if you have protected data and
other programmer extends from the class, it is
hard to change the implementation then ...)
Static keyword
- static field do not change from one instance of a class to another
("belong" to the class)
- static method belong to a class and do not operate on any instance of a class
(We can use the method without creating an instance of a class.)
Example:
double x = Math.pow(3, 0.1);
- ClassName.staticMethod(parameters);
- ClassName.staticFieldName;
- data is often private
- control how data is changed
- provide error checking
- provide read-only access
- allow class to change what data it uses without
affecting users
Examples:
class Fraction
{
// Member data.
private int numerator;
private int denominator;
// Constructors.
public Fraction ()
{
numerator = 0;
denominator = 1;
}
public Fraction (int n, int d)
{
numerator = n;
if (d != 0)
denominator = d;
else
denominator = -9999;
}
// Member methods.
public int getNumerator ()
{
return numerator;
}
public int getDenominator ()
{
return denominator;
}
}
toString() method
- returns String representation of the object
- used in System.out.println () and String concatenation
- useful for debugging
- default is the class name plus a meaningless number
- you can provide a more meaningful String representation
- always public
Examples:
class Fraction
{
// ...
public String toString ()
{
return Integer.toString (numerator) + "/"
+ Integer.toString (denominator);
}
}
The this Object Reference
The keyword this refers to the object on which the method
operates
Example: Java Date class has a toString() method that prints
out the object
The current date stored in a date variable will be:
this.toString()
Example:
class Account
{
public Account(String n)
{
this(n, Account.generateKey());
}
public Account(String n, int key)
{
customerName = n;
accountNum = key;
}
...
}
Destructors
- "Kind of" does not supported by Java, we use:
- finalize ()
It will be called before the garbage
collector sweeps away the object
- used to clean up when an object is destroyed
- called by garbage collector
- not reliable!
(Do not know when it is going to get called)
- Add your own clean up, say dispose, and call it yourself
!
Packages
- provide a way of grouping similar classes
- first line of source file names package
- package MyPackage.SubPackage.etc;
E.g. java.lang, java.util, java.net
- default is the "unnamed" package
- must "qualify" using the package name
- import MyPackage.SubPackage.myetc.MyClass;
We called this nesting packages - guarantee the
uniqueness of package name
- import MyPackage.SubPackage.myetc.*;
- Java maps package name to directory path
- convention is to use "reverse" email domain
- If your source file has no package declaration, Java adds
the classes in it to its default package
- Compiler can locate Packages by looking into the right
directory
CLASSPATH=c:\jdk\lib;c:\MyPackage;.
- There is no java\util in c:\jdk\lib ... instead a
classes.zip file will be in
- Java always searches the java.lang package (never need to
specify it)
Examples:
package edu.umn.JavaClass; // import a specific class
class Fraction
{
// ...
}
Class design hints
- make data private
- initialize data in construtor or in definition
- not all data needs a getData() and setData() method
- Suggested Format:
public features
package scope features
private features
(constants
constructors
methods
static methods
instance variables
static variables)
- break up large classes into smaller classes
- name classes, data, and methods appropriately
- class names - start with uppercase letter, use a
noun
- data names - start with lowercase letter, use a
noun
- method names - start with lowercase letter, use a
verb
Object wrappers
- primitive data types like int, float, boolean are not
objects
- Java provides object wrappers for these: e.g. Integer,
Float, Boolean
- needed when using such data in Vectors or other places
expecting an object
Lab
Create an inventory application for a retail store. Your
application should be made up of 3 classes:
- A class called StockItem
which represents a stock item in an inventory. It should
have:
- a private int that is an id number
- a private String that is the name of the item
- a private double that is the price of each item
- a private int that is how many of these items are
in stock
- a constructor that initializes each of the four
data members (it should take four parameters)
- toString(), a method that returns a string in the
form:
name (id)
- purchase(), a method that takes the number to
purchase as an int parameter, and returns the
cost of the items. It should also decrease the
number of items in stock.
- restock(), a method that takes the number of
items to add to stock as an int parameter - it
does not need to return anything.
- A class called CustomerTransaction
which represents a customer purchasing some items. It
should have:
- a private double that is the running total of the
transaction.
- purchase(), which takes a StockItem and a
quantity as parameters, adjusts the inventory
appropriately, and adds the price to the running
total.
- pay(), which takes the amount tendered by the
customer as a parameter, and returns the amount
in change.
- A class called Week4 which is
really just for the main() method of the application. It
should:
- Create 4 StockItem objects.
- Create a CustomerTransaction object.
- Simulate the customer purchasing some items.
- Simulate the customer paying for the items.
- Print out the change.
Copyright
1996-2001 OpenLoop Computing. All rights reserved.