Object-Oriented Programming

  1. Encapsulation
  2. Inheritance
  3. Polymorphism

Abstraction: Focus on what instead of the how.

Default Methods for All Objects

Specifying Methods

Preconditions

Postconditions

Assert Statement:

Format: assert <expression> : "<message>

Example: Using assert
assert head != null : "head is a null pointer"

Abstract Classes and Methods

Abstract Classes

Format:

public abstract class ClassName

Abstract Class:

Abstract Methods

Format

AccessSpecifier abstract ReturnType Methodname(ParameterList);

Abstract classes are drawn like regular class in UML, except the name of the class and abstract methods are italicized.

Non-abstract classes are called concrete classes.

Java Interfaces

Interface: Program component that declares a number of public methods.

Note: Java only supports single inheritance

Example: Using an interface
  1. The interface:
public interface Measureable {
  double getPerimeter();
  double getArea();
}
  1. At the top of the Circle class:
class Circle implements Measureable

In this example you can have a Measureable reference variable that can reference objects of any type that implement Measureable, like so:

  1. Somewhere in the client:
public class Client {
  public static void main(String[] args) {
      Measureable c = new Circle();
      c.getArea();
  }
}

Note: Default Methods

Interface v.s. Abstract Classes

Use an abstract class if you want to:

  1. Provide a method definition, or
  2. Declare a private data field that your classes will have in common.

Choosing Classes

  1. Who’ll use the system?
  2. What can each actor do?
  3. What scenarios involve common goals?

Example: Designing a registration system for a school

Users:

Common Things Student and Registrar Can Do:

CourseSchedulecourseCountcourseListenroll()add()drop()displaySchedule()changeAddress()

UML Interface Example

MeasureablegetPerimeter() : doublegetArea() : doubleCircleradius : doublegetPerimeter() : doublegetArea() : double

Reusing Classes

Most software is created by reusing existing components.