Object-Oriented Programming Overview

Concepts

Packages

A package (namespace in C++) is a named collection of related class and interface declarations.

Packages may also contain sub-packages.

If a package A references items defined in package B we say that A depends on B. In Java A can explicitly import the needed definitions from B.

Packages allow name sharing among classes and interfaces.

Names can be disambiguated by using their qualified names. For example:

java.awt.List

java.util.List

UML package notation:

Classes, Objects, & Interfaces

A class is a collection of related method and variable (field) declarations.

class Account {
   double balance = 0.0;
   void withdraw(double amt) { balance -= amt; }
   void deposit(double amt) { balance += amt; }
}

An object is an instance of a class. It contains variables and methods.

Account savings = new Account();
Account checking = new Account();

An abstract class cannot be instantiated.

abstract class Shape {
   int xc, yc; // upper left corner of bounding box
   int height, width; // height and width of bounding box
   void move(int xc, int yc) {
      this.xc = xc;  // this = implicit or executing object
      this.yc = yc;
   }
}

An abstract method has no implementation. For example:

abstract void drawShape();

If a class contains one or more declarations of abstract methods, then it is abstract.

abstract class Shape {
   int xc, yc; // upper left corner of bounding box
   int height, width; // height and width of bounding box
   void move(int x, int y) {
      xc = x;
      yc = y;
   }
   abstract void drawShape();
}

An interfaces is a collection of related abstract method declarations (no variables or methods). For example:

interface Comparable {
   // 1 = greater, 0 = same, -1 = less
   int compareTo(Comparable other);
}

interface Cloneable {
   Cloneable clone();
}

interface Alarm {
   void notify();
}

A class can implement multiple interfaces if it provides implementations for all of the interfaces' abstract methods.

class RationalNumber implements Comparable, Cloneable { ... }

Inheritance

A class can extend another class. If so it inherits all of the members (fields and methods) of the extended class.

class ControlPanel extends Window { ... }

An interface can extend another interface. If so it inherits all of the abstract methods of the extended interface.

interface Arithmetic extends Comparable {
   Arithmetic add(Arithmetic other);
   // mul, sub, div, etc.
}

Encapsulation

The visibility/scope of classes, interfaces, fields and methods can be restricted.

Here are some popular scopes:

private

protected

public

package

For example:

public class Account {
   private double balance = 0.0;
   public void withdraw(double amt) { balance -= amt; }
   public void deposit(double amt) { balance += amt; }
}

Constructors

A class should provide constructors for initializing fields:

public class Account {
   private double balance;
   public Account(double balance) { this.balance = balance; }
   public Account() { this(0.0); }
   public void withdraw(double amt) { balance -= amt; }
   public void deposit(double amt) { balance += amt; }
}

class CorporateAccount extends Account {
   public CorporateAccount(double balance) { super(balance); }
   public void deductFees() { /* no fees! */ }
}

Polymorphism

Assume A and B are classes or interfaces. A is a subtype of B (A <: B) if

·      A = B

·      A extends or implements B

·      A extends or implements a subclass of B

The subsumption rule states:

   If A <: B, then a variable or parameter of type B may contain instances of type A

For example:

class Shape implements Serializable { ... }
class Polygon extends Shape { ... }
class  Rectangle extends Polygon { ... }

And so:

Rectangle <: Polygon <: Shape <: Serializable <: Object

And the following assignments are allowed by the subsumption rule:

Polygon p = new Rectangle();
Shape s = p;

However, the following call fails, why?

int n = s.numSides();

Generics Collections

A generic class is parameterized by one or more types (classes or interfaces).

class Cell<T> { T data; ... }

A generic collection is parameterized by the types of objects it stores. For example:

List<Event> schedule = new LinkedList<Event>();

Set<Person> members = new HashSet<Person>();

Map<Seat, Passenger> seats = new HashMap<Seat, Passenger>();

Notes on Java Collections Framework: http://www.cs.sjsu.edu/faculty/pearce/modules/lectures/j2se/jcf/index.htm.

Notes on Java Maps: http://www.cs.sjsu.edu/faculty/pearce/modules/lectures/j2se/jcf/Maps.htm.

Notes on C++ STL: http://www.cs.sjsu.edu/faculty/pearce/modules/lectures/cpp/advanced/STL.htm.

Exceptions

If a method detects an error, it should throw and exception:

class Account {
   double balance;
   public Account(double balance) { this.balance = balance; }
   public Account() { this(0.0); }
   void withdraw(double amt) throws Exception {
      if (balance < amt) throw new Exception("Insufficient Funds!");
      balance -= amt;
   }
   void deposit(double amt) { balance += amt; }
}

Exceptions are usually caught in the programs controller:

try {
   checking.withdraw(1000000.01);
}
catch(Excaption e) {
   System.err.println(e);
}

Reflection

In modern OOP languages objects also provide meta-information:

Class componentClass = component.getClass();
Method[] methods = componentClass.getMethods();
methods[0].invoke(args);
// etc.

This is useful for plug-and-play architectures where components can be added to a system after it is deployed.

Lectures on reflection (Java & C++): http://www.cs.sjsu.edu/faculty/pearce/modules/lectures/oop/types/reflection/index.htm.

Examples

Calculators

simpleVM

Lectures

Object-Oriented Programming

Java Programming

OOP Labs

Lab 1

An eStore provides shoppers with a cart. A cart has a shipper and contains items. Items include appliances, tools, toys, clothes, and other categories we haven't thought of yet. Each item has a unique ID number. This is a string such as "Tool:3001". Each item has a price. A cart computes the total of all items it contains plus the shipping cost. There are several choices for shipping: land, air, and sea. Implement and test these classes.

Calculator Labs

Lab 2

Look up the formulas for computing compound interest and monthly payments (i.e., to repay a loan). Use this to complete and test the implementation of BusinessCalculator, which extends Calculator.

Lab 3

We say that ScientificCalculator extends or is a subclass of Calculator. Equivalently, we say that Calculator is a superclass or base class of Calculator.

Polymorphism means that instances of ScientificCalculator can masquerade as instances of Calculator:

Calculator c = new ScientificCalculator();

However, we get into trouble here:

c.sin(); // error

How can c be safely re-typed so that the sin function can be called?

Lab 4

ScientificCalculator inherits all of the members of Calculator, including those members Calculator inherited from its superclass. Although not explicitly declared, the super class of Calculator is Java's Object class. The Object class provides methods such as toString, hashCode, equals, and getClass. Add code to determine if calc1 and calc2 (declared in TestCalculator.main) are equal. Find out the true class of calc2 (as opposed to its type). How does Java convert calc2 into a string? Why is hashCode needed for all objects?

Lab 5: Overriding versus Overloading

Overloading means name sharing: several methods can share the same name (provided their parameter lists are different).

Overriding means redefining an inherited method. In this case it's important that the parameter lists are the same.

Overload the sin, cos, and tan methods for ScientificCalculator with versions that simply assign the value computed for an input to the result field:

result = Math.sin(input);

Override the inherited toString method for ScientificCalculator that prints something more user friendly.

VM Labs

Finish the VM labs.