Wednesday, January 31, 2007

Lecture 11


  • Objects that inherit features of a parent class can be thought to contain an object of the parent type
  • all methods and fields of the parent are "inherited"

Best Practices With Inheritance
  • discard packaging
  • make all instance fields private
    • this means instance fields are not visible to child methods
    • if you need to access instance fields of the parent from the child use the public interface

Why Do This?
  • child inherits parent's methods and therefore inherits the public interface
    • this simplifies access
    • and prevents privacy problems via inheritance

public class Parent
protected mutable class x;

public class Child extends Parent
{public mutable class leakyMethod()
{return m;

  • form part of the public interface

public class Child extends Parent
public child ( ...parameters for child / parent )
//call parent constructor
super(...parameters for parent)
//assigns child parameter

Overriding Methods

  • Child classes inherit all methods from the parent
  • child has the option to re-implement these methods
    • called overriding

  • All objects extend type Object by default

public class MyClass [extends Object]
  • type object contains several default methods
    • equals(), toString(), clone()

  • declaration of an overridden method in the child must be exactly the same as the parent
    • same return type
    • same parameter type
    • same number of parameters


public int myMethod(double a, int b)


public int myMethod(double a, int b)

  • if myMethod is overridden in a child class, use 'super.myMethod' to gain access to the parent method
  • to prevent overriding use 'final'

Abstract Classes

  • a student is either graduate or undergraduate
    • there is no 'plain' student
  • so it doesn't make sense to instantiate this class
  • all students have letter grades
  • child classes of student should be forced to implement getLetterGrade()


  • declare Student an abstract class
    • can't instantiate an object of type student
  • declare getLetterGrade() an abstract method within abstract class student
  • children must override getLetterGrade() or they will be abstract classes themselves

public abstract class Student
public abstract String getLetterGrade();


Tuesday, January 30, 2007

Lab Test 1 Finished Impressions

today I finished the LabTest
i found it difficult, it was basically like starting a half finished lab from previous weeks.
key things on it were

  • JavaDoc
    • know @param and @return
    • know /**, */ are the opening and closing parenthesis
  • Copy Constructors
    • know how to deep copy
    • know what kinds of classes need to be copy constructed
      • only mutable classes need a copy constructor
  • Understand how to make methods from scratch, such as equals() and toString()
  • aside from that , just study what goes in a constructor
    • and how to test it.

Monday, January 29, 2007

LabTest 1 Impressions

Here you can post how you felt the test went, give pointers to those who haven't taken it and so on.

  • We asked Andrew about test specifications
    • he said 'In the book, so far we have done chapters 3 and 9, and a little bit of chapter 13.'
    • he also said the best way to study for it is lecture notes, as there is material he skipped that we shouldn't have to be tested on
    • he said the Lab Tests will commonly be
      • editing sample code that doesn't work
      • make a class w/ a given API
      • make a class of your own that meets specs (similar to what we've done in lab1 / lab2

Off topic from the test...

how do you guys feel about the lab TA's?
I want Maan back, I can never really get much coherent help.. but if you guys know a good TA i should be talking to .. post their name on here for me.

  • Andrew posted this on his site about test:

Lecture 11


  • say we are implementing a database of students in a course
    • course is open to both undergraduate and graduate students
    • obviously, the student records will be largely the same
  • All students have
    • Name
    • Student Number
    • Raw Percentage Score
  • calculation of the letter grade is different between these students
  • Undergrad
    • A 80-100%
    • B 70-80%
    • C 60-70%
    • D 50-60%
    • F <50%
  • Graduate Student
    • A 80-100%
    • B 70-80%
    • F <70%
  • inefficient to implement two separate classes when they overlap so much
  • intuitively, both an undergrad and grad are types of students with certain features in common. it would be nice if student class could handle common functions and that this class could be extended
  • Java allows us to extend this way using inheritance
    • use the 'extends' keyword to declare child classes
public class Student
//parent class
//takes care of common features
//student name / number / raw score


public class underGradStudent extends Student
//undergrad letter grade calculation


public class gradStudent extends Student

//grad letter grade calculation


Inheritance and Constructors

  • if you provide no constructor in a child class that will lead the compiler to call the default constructor of the parent and will generate an error if that doesn't exist.
  • provide a constructor
    • presumably you went to call the constructor of the parent class
  • use the keyword 'super' (works like keyword 'this')
Access Specifiers

  • private members are hidden from children
  • this is sometimes valuable to have internal hidden variables that can't be manipulated outside your class
  • protected objects are visible to children but not the public
Package and Access Restrictions
  • four valid access specifiers
    • private
      • most restricted
      • class file only
    • nothing
      • access within package
    • protected
      • access within package and children
    • public
      • accessible everywhere
  • ignore packages
    • and java puts all files in the same package
  • package
    • package level access throughout the code
Creating and Using Package

  1. Create a package
    1. think of a name for package
      1. all lower case letters
    2. create a directory with that name
      1. move all files to that directory
    3. in all files in student write the following statement as the first line
      1. package student;
    4. using the package
      1. at the top you write the following
        1. import student.*;

Saturday, January 27, 2007

Lecture 10

  • Delegation within the class definition
    • code is sometimes used over and over within the methods of a class
    • constructors =>implement the constructor that takes all possible arguements and call that constructor from the other constructors.
  • why do this?
    • saves you time
    • making changes is much easier, and less error prore(eg. you might miss a change.)
  • Constructor Fields(final keyword)
    • best practice to use a variable to store any constants used by your program
    • want these values to be protected from change
  • public final int CONSTANTS = s;
    • constant is initially given the value s
    • no entity in the program is allowed to alter constant
    • final entities must be initialized on the same line that they are declared
    • stylistically, final variables are always written in all caps.
  • why use constants?

private int x
private final int MAX = 500;
if (x > MAX - x ) { }
    • -there are other uses of final
  • method class
    • inheritance
  • variable
    • constant
  • The constant feature only works with primitives
  • if you declare an object final, that object does not magically become immutable
  • Preconditions and postconditions as the system programmer, you have a contractual relationship with the application programmer.
  • AP calls your methods satisfying conditions which you specify
  • eg. amount >= 0 indeposit(), withdrawal
  • Postcondition:
    • In return, you agree that the method output satisfies given conditions
    • Example: getbalance() returns the correct balance
    • Preconditions dont need to be checked
    • postcondition should be checked during debugging
    • assert checking to ensure postconditions be satisfied
    • pre and postconditions must be specified in javadoc

Wednesday, January 24, 2007

Lecture 9

Special Functions
  • already we have seen clone()
    • this is a special method that is possessed by all objects
  • we will talk about two more in this lecture
    • toString()
    • equals()
  • returns an object of type String
  • 'cast' your object object to a string type
  • creates a string output of your objects current state
    • contents of all private instance fields
  • very useful for debugging
  • the compiler uses toString() whenever it needs to cast your object to a String

MyObject x = new MyObject();

  • println takes a String argument
  • this is equivalent to saying:
  • System.out.println(x.toString());
  • In a toString method you should do the following
    • include the name of the class
    • include all the private fields
  • if MyObject contains only a private int a
    • toString() output should be
      • MyObject[a=0]
  • returns a boolean
    • true or false
  • checks to see whether two objects are equal
  • returns true if they are equal, false if they are not
The default form of this method is

Public boolean equals(Object, OtherObject)

  • we must use the most general form of the default equals() in order to capture all objects
Public Class MyObject{

private int x;
public boolean equals(Object, OtherObject){
MyObject other = (MyObject)OtherObject;
return (this.x == other.x);

  • if x and y are objects and not primitives then
    • x==y if x and y point to the same object
Delegation within the class
  • Example: code used by many methods in the same class
  • Example: Constructors

Monday, January 22, 2007

Lab 2

Please Post your ideas for Lab 2 here! I haven't started yet, my labs are on tuesday!

For Lab Instructions: Click

Lecture 8

Scope of Variables

  • how far are the declared variables visible in code?
  • when is it safe to refuse variable names?
  1. Local variables within a method
    1. always applies to the method parameters
    2. the scope of local variables is the set of {} that contains the definition
    3. this is usually, but not always, the braces {} surrounding the entire method
    4. not allowed to have two variables of the same name within the same set of braces{}

public void method(){ int x=o; int x=5; // illegal }

Example 2

public void method(){
x=0 //illegal

if (y==5)
{ int x = 0;
else {
int x = 5;

  • x is only accessible through the scope of {} between if and else
  • putting x = 0 at the top is illegal because it is outside the desired scope

2. Local variables vs. Instance Fields

public class BankAccount{
Private double balance;
public void method ()
double balance; //legal
balance = 0; // legal - this is legal because local variables take precedence

this.balance = 0; // instance field relates to balance

3. Multiple Objects

  • methods of an object can see private fields of any object of that class

private double balance

public void method(BankAccount x){
balance = 0; //current object
x.balance = 0 // other object

// if user typed x.method(y) then x would relate to
balance = 0 and y would relate to balance = 0

Clone, shallow copies, deep copies
  • implement copy constructors to perform defensive copies which avoids privacy leaks
  • you may be tempted to use the method clone() as an easy copy constructor.
  • the only time to use clone() is if no copy constructor is defined.

MOWC a,b;
a = new MOWN();
b=a.clone(); // creates a shallow copy of a and store it in b

// this is similar to but not identical to using the copy constructor

what does clone do?
  • creates a bitwise copy of the object


{ int a,b;
private myobject c;}
// my object is mutable}

x = new MOWC():
//this example would give a reference to myobject c even if copied it will reference the same object instead of a new

  • two references
  • changes y to show up in x
  • privacy leak
  • this is a shallow copy
  • clone() implements a shallow copy, which does not respect the semantics of the object it copies
  • shallow copies can lead to a privacy leak
  • Deep Copy
    • implements a copy constructor

public class MOWC(MOWC in){
a = in.a;
c= new myobject(in.c);
//this is the correct way to deep copy

  • shallow copy is safe if your object contains
    • primitives
    • immutable classes
  • deep copy is mandatory if object contains mutable classes
  • From Now On
    • properly implement a copy constructor for all mutable classes that you design
  • Only
    • use clone() if no copy constructor exists

Friday, January 19, 2007

Lecture 7

  • an automated tool for documentation and generation of your java code
  • operates through the comments in your java code

Remember: Java Comments

//... -> is a single line comment

/* ... */ -> is a multiline comment

/** ... */ -> format used for Javadoc documentation

Note: for this documentation '...' refers to details you filled in.

  • document every public entity in your code
  • place the /** ... */ comments (Javadoc comments) immediately prior to each public entry
  • Entries that should have Javadoc comments:
    • the class itself
    • the constructors (public)
    • the methods (public)
    • any public fields
  • any non-Javadoc comments will be ignored by Javadoc. So you can still comment your code as necessary

/** this class contains a BankAccount balance and provides methods for manipulating that balance */

public class BankAccount {

/** this is the default constructor which sets the balance to zero */

public BankAccount(){balance=0;}

//info goes here

private double balance;
//no Javadoc comments here, because this is not part of the public
//even if Javadoc sees Javadoc comments here it will avoid when rendering itself

  • Javadoc has special keywords used within a Javadoc comment to document parameters and return values
    • @param - parameters
    • @return - return values

/** Add a deposit to the current balance
@param amount amount of the deposit

public void deposit(double amount){
balance = balance + amount

Example 2

/** returns the current balance
@return The value of the current balance

public double getbalance(){return balance;}

//double is a 'non void' return value


  • if you have more than one java file in the folder you wish to create a Javadoc for
$javadoc *.java
  • this creates many different files that will be included in the Javadoc file. to access the file in a webbrowser open index.html
Javadoc Practices
  • Javadoc documents the public interface of your code (everything w/ the public tag)
  • it's up to you to provide descriptions. Be as detailed as reasonable
  • good practice to produce Javadoc at the same time as the public interface
  • Always Document your Code!!!

Wednesday, January 17, 2007


Disclaimer: haven't programmed Java since last semester, feels like i lost quite a lot of skill, anyways i conjured up this much. it basically does everything in the details that Andrew asked for, HOWEVER , i am completely useless when incorporating a monthly compiler. I'm guessing i'll have to use the Calendar class... any ideas? please post code / remarks on this page. I think the best way to tackle labs will be using this blog.

anyways here's what i got so far, it compiles so you can see what i'm up to usin the that Andrew provided.. quicklink to the assignment: Click


public class BankAccount {

// Constructor

public BankAccount() {
balance = 0;


public BankAccount(double balance, double interest)
this.balance = balance;
this.interest = interest;
this.monthfee = 10;
this.deposittotal = 0;
this.withdrawtotal = 0;
this.overbalance = 5000;
this.overdeposit = 200;

// Methods

public void changfee(double monthfee) {
this.monthfee = monthfee;


public void deposit(double amount) {
balance = balance + amount;
deposittotal = deposittotal + amount;

public void withdraw(double amount) {
balance = balance - amount;
withdrawtotal = withdrawtotal + amount;

public double getbalance() {
return balance;

public void changeob(double overbalance) {
this.overbalance = overbalance;

public void changedep(double overdeposit) {
this.overdeposit = overdeposit;

public void changeinterest(double interest) {
this.interest = interest;

public void compilebalance() {

//class that compiles all fees and interest

balance = balance + (balance * interest);
if (balance > overbalance)
monthfee = 0;

if ((deposittotal - withdrawtotal) > overdeposit)
monthfee = 0;
balance = balance - monthfee;


// Instance Fields

private double balance;
private double interest;
private double monthfee;
public double deposittotal;
public double withdrawtotal;
private double overbalance;
private double overdeposit;

Lecture 6

Objects vs. Primitives
  • 4 integer types - byte, short, long, int
  • 2 floating point types - float, double
  • 1 Boolean
  • 1 char
  • remember if A and B are objects and we write a=b
  • then a is A is a reference to B, A is NOT a copy of B
  • the exact opposite occurs when A,B are primitives
  • reference passing can happen in 3 ways:
    • a=b
    • parameter passing
    • return value passing
  • privacy violations can occur unless you are careful
Defensive Copying

  • Defensive copying is used to force all interactions w/ private fields to go through the public interface (example: through the class methods)
  • Defensive copies of mutable objects are always performed when an object is into or out of a class (Shield the reference from the outside world)
  • Constructors (in) - as parameters
  • Accessors(out) - as return values
  • Mutators (in) - as parameters
public myclass accessor(){
return x; //BAD!!
//this is bad becuase it passes the reference outside the class

myclass copy_of_x = new myclass(x);
return copy_of_x; //OK!!

Example 2

public void mutator(myclass x_in){
x=x_in; //BAD!!
//because whoever called the mutator pertains a reference to x_in, which is a direct reference of x.

myclass copy_of_x_in = new myclass(x_in)
copy_of_x_in // GOOD!!

Immutable Classes
  • an immutable class is a class whose private fields cannot be changed after construction
  • a mutable class is the opposite and can change after construction
  • an immutable class has the following properties
    • all instance fields are private
    • no mutators
    • and either
      • all private/instance fields are primitives
      • or themselves a primitive
    • or
      • defensive copies are always made of any mutable classes
  • if a class is truly immutable then defensive copies do not need to be made of it
    • therefore it's perfectly OK to share references of mutable classes
    • this saves memory
  • Immutable classes do not require copy constructors
  • mutable classes MUST have copy constructors (for defensive copying)

Lecture 5

Static Fields

  • an instance field is a field contained within each and every object of a particular class
  • a static field is a field for the entire class
    • one for the entire class
    • can access a static field w/o instantiating any objects
Example 1

  • can be used to store constants in a utility
private static double pi = 3.14
public static double getpi(){return pi;}

Example 2

  • Can use a static field to keep track of the number of instances of a class.
Caution about static: do not over use it
  • if you make everything static then objects and classes become meaningless
  • is will no longer be object oriented if static classes are only involved
Copy Constructor

  • a special kind of constructor that is used for copying objects
  • how do we create a new object that is a copy of an existing object?

myobject x,y;
y=new myobject();
y=x; // this is bad!!!

  • this does not create a copy, it makes y another name for x. if i make changes to y, those changes also occur to x.
  • this also works both ways
  • Copy Constructor is the proper strategy
public class myobject {//two private fields: a,b
public myobject (myobject Source) {
//'Source' is the variable name
//copy constructor
a = source.a
b = source.b

x = new myobject();
y = new myobject(x);


  • this raises important points about Java objects:
    • the variable name is only a reference to the object. it does NOT contain the object itself
    • that's why y=x does not COPY
      • it makes y a reference to x
    • this is true for all objects in Java.
  • Exception to this rule
    • primitive types are not objects
      • byte (8 bit)
      • short (16 bit)
      • int (32 bit)
      • long(64 bit)
      • float(real number - 32 bit)
      • double(real number - 64 bit)
      • Boolean(true/false)
      • char(Unicode character)

int x,y
y=x //this is OK, y will make it's own primitive w/ value 5 while x will also be separate from y

Mutable Classes
  • mutable classes have private fields that can change after instantiation
Immutable Classes
  • not allowed to change after construction
  • the reference is passed not only when = occurs, but also whenever objects are passed around
    • method parameters
    • return values
  • privacy violations occur unless care is taken to properly copy objects

Lecture 4

Employee Database

  • say you are implementing an employee database
  • Employee' will be an object
  • Employees start out w/ an employee number which is given but never changes
  • default salary is $40,000 which can change or start different
  • employees have names which are initially given but CAN change

  • Need to be able to read:
  • Name
  • Employee Number
  • Annual Salary
  • Monthly Salary

  • these are the 'accessors' for the program.

public class Employee {

public Employee (String name, int enum, double salary)
public Employee (String name, int enum)
//methods: accessors
public String GetName()
public int GetEmNum()
public double GetAnnSalary()
public double GetMonSalary()
//methods: mutators
public void SetName(String Name)
public void SetSalary(double salary)
private String EmployeeName;
private int EmployeeNumber;
private double EmployeeSalary;

  • after writing this on the board Andrew carried on w/ code he prepared before class

Utility Classes And The 'Static' Keyword

  • a utility class is a special class w/ no fields that only provides methods that are useful to other objects.
  • example: java.lang.math

Why Have Utilities?
  1. to organize useful methods in a matter similar to objects
  2. use methods w/o involking storage

double x;

  • the keyword 'static' is used to refer to methods that can be used independantly of objects

class myClass {
public static void mymethod(){}

myClass mc = new myClass();
//legal to say
//also legal to say
myclass.mymethod(); //better practice
//legal to use even if no objects of type myClass exist

ample 2

public class myutil{

public static int addint(int a, int b){

return a+b;



c= myutil.addint(3,4;



return: 7

  • Can prevent the compiler from crashing an object relating to a utility class
    • use a private constructor

private myutil(){}

// prevents someone trying to make a 'myutil' object

  • now no outside class has the right to execute the constructor, so an object type util cannot be created.

Lecture 3

Continuing Bank Account Example

  • include the BankAccount object in a real program in order to use it.
  • a valid java program must contain a class w/ the special method 'main'


Public class mybank {

public static void main (string args[]) {

BankAccount mysavings = new BankAccount();

// 'new' is a java keyword
//the brackets are parameters passed to the constructor - to be explained in later lecture on overloading




//this is in console

javac -cp .
//-cp allows compiler to search current directory for class files


- 500
- 250

Multiple Constructors

  • the constructor can be overloaded

  • it can be multiply defined w/ different parameter declarations
  • previously we had:

public BankAccount() {balance = 0}

we could also have

public BankAccount(double id) {
balance = id;


BankAccount ac1 = new BankAccount();
BankAccount ac2 = new BankAccount(100);

  • java keyword 'this'
  • is a place holder for current method

public void deposit (double amount);
//balance = balance + amount // this is the old syntax we used
this.balance = this.balance + amount // using 'this'

  • both of these are legal

public void transfer (double amount, BankAccount x)

this.balance = this.balance - amount;
x.balance = x.balance + amount;

public BankAccount () {balance = 0;}

public BankAccount (double id) {balance = id;}

public BankAccount(){this(0);}

this(0); MUST be on the first line of the constructor and also calls the constructor.

To Review:

designing and implementing a class

  1. Consider the requirements of the class (system methods)
  2. Specify the public interface
    1. method declaration.
    2. Constructor declaration.
  3. Determine the instance fields
  4. implement methods
  5. test the object

Lecture 2

Class Definition and Syntax

  • from last time we had the class BankAccount
  • with methods
    • withdraw, deposit, getbalance
  • the bank account has a hidden balance that is only accessable via the methods.

Method Definition Syntax

public void deposit (double amount)
public void withdraw(double amount)
public double getbalance()

  • these are seperated by : access specifiers (public), return type (void,double), method names (deposit, withdraw, getbalance) and method parameters [double amount, ()]
  • every class representing an object requires a special method called a constructor
  • the role of the constructor is to properly initialize any hidden data fields (eg. sets balance to zero as default)
  • this is always executed when new instances of the class are created
  • the name of the constructor method is the same as the name of the class
  • constructors have no return type, not even void
  • you cannot have a method w/ the same name of the class unless it is a constuctor
  • Object classes contain fields of private data. Not accessible to the user or Application Programmer(AP)
  • example: (Balance, account number, account holder, etc.)

Class Declaration Syntax

public class BankAccount {

//constructor declataion

// methods

//private data


  • we can fill in the method declarations (including the constructor methods) as follows:

Class Declaration Syntax

public class BankAccount {

public BankAccount() {

//constructor statements

public void deposit(double parameter){

// deposit statement


public void withdraw(double amount){
//withdraw statement
public double getbalance()
//getbalance statements

//private declatarations


  • what was written is the public interface of the class.
  • these methods are the only way for the AP to interact w/ the class
  • this forms the basis of the API
  • filling in the details
  • consider the private data
    • private data we called Instance Fields
    • fields of data for every instance of the object
  • access specifier, type and name

private double balance;
private int accountnumber;

  • private:
    • not accessable outside the object
    • not part of the public interface
    • accessible to methods in the class

Public class BankAccount {
private double balance; //instance field
public BankAccount() {balance = 0;} //constructor
public void deposit (double amount) {

balance = balance + amount; // method

public void withdraw (double amount) {
balance = balance - amount; //method