OOP

CSCI 1913 – Introduction to Algorithms, Data Structures, and Program Development
Adriana Picoral

Classes

  • Collection of methods and attributes (information/values)
  • Template, blueprint of cookie cutter to construct many objects

Modularity: Classes allow us to split the problem to be solved into distinct tasks

You should be able to think about what a class does, not how it does it

Object Oriented Programming (OOP)

  • Programming paradigm
  • Code is organized in objects
  • Objects contain both data (attributes) and functions (methods)

Why OOP?

  • Represent complicated objects
  • Provide meaningful manipulations
  • Enforce invariants about data
  • Hide difficult details
  • Decompose code differenty

Class vs. Object

Class - A blueprint or template that defines the structure and behavior of objects.

public class MyTime {
  
}

Object/Instance - A concrete realization of a class. If a class is the blueprint, an object is the actual house built from it.

MyTime time = new MyTime();
  • Each object is an independent copy of the Class
  • Creating objects from a class is often called instantiating the class

Keyword new

The keyword new does three things:

  • finds space in memory for the new object
  • calls the constructor to initialize the object
  • returns the location in memory where the object resides

Class vs. Object

  • A Class definition is like the plan for a house
  • An Object is like a house built according to the plan
  • Many houses can be built following the same plan
  • The existence of a plan does not mean a building exists, but once a plan exists, one or more buildings can be built to the plan spec
  • Similarly, many Objects can be created from a Class definition

Parts of a Class

Attributes/Properties/Fields - Variables that belong to a class or object, storing data about that object’s state.

public class MyTime {
  private int seconds;
  
}

Methods

Methods are functions defined inside a class that describe behaviors or actions an object (or class if the static keyword is used) can perform.

Types of Methods:

  • Constructor
  • Getter
  • Setter
  • Operator
  • Helper

Constructor

A special method that runs automatically when creating a new object, typically used to initialize attributes.

  • No return type, same name as class
  • There should be at least one public constructor, but there could be private constructors as well.

Constructor

  • Constructors are the only type of method that has no return type
public class MyTime {
  private int seconds;
  
  public MyTime(int seconds) {
    this.seconds = seconds;
  }
  
}

this – A reference to the current instance of the class, keyword used to differenciate between the instance variable and the parameter name

Getter and Setter

  • Getter/Accessor - Methods that retrieve (read) the value of private attributes.
  • Setter/Mutator - Methods that modify (write) the value of private attributes, often with validation.

Getter and Setter

These are usually public – used to access and modify instance variables

// getter
public int getSeconds() {
  return seconds;
}

// setter
public void setSeconds(int seconds) {
  this.seconds = seconds;
}

Encapsulation

Bundled data and methods together (getters/setters) while hiding internal details and controlling access to them.

  • Generally attributes should be private, and those that are intended for general use will have public accessors (getters and/or setters) with validation for setters

Operator vs. Helper

  • Operator methods – use public keyword to provide external way to perform an operation – example: add complex numbers, subtract complex numbers

  • Helper methods – Use private keyword to perform operations that are used internally by other methods. These are intended for internal use within a class to support other methods, typically not meant to be called directly from outside the class.

Helper methods are usually used to break down complex operations into smaller, reusable pieces. Operator methods often call helper methods.

Operator and Helper methods

This does not complete the class code, what else do you need to make this class work as intended?

public String getHMS() {
  return hours + ":" + minutes + ":" + seconds;
}

private int getHours() {
  return seconds/3600;
}

private int getMinutes() {
  return seconds/60;
}

What instance variables do we need?

Complete the Class

What code do you need to write to have this main method work?

public static void main(String[] args) {
  MyTime time = new MyTime(3661);
  System.out.println(time.getHMS());
}

Submit your MyTime.java file to gradescope.

Solution with Object Instantiation

public class MyTime {
  
    public MyTime(int seconds) {
        secondsLeft = seconds;

        // get full hours
        hours = getHours();

        // update how many seconds are left
        secondsLeft = secondsLeft - (hours * 3600);

        // calculate full minutes
        minutes = getMinutes();

        // update how many seconds are left
        secondsLeft = secondsLeft - (minutes * 60);
    }

    public String getHMS() {
        return hours + ":" + minutes + ":" + secondsLeft;
    }

    private int getHours() {
        return secondsLeft/3600;
    }

    private int getMinutes() {
        return secondsLeft/60;
    }
    
    private int secondsLeft;
    private int hours;
    private int minutes;

    public static void main(String[] args) {
        MyTime time = new MyTime(3661);
        System.out.println(time.getHMS());
    }
}

Modifiers

Static vs. non-static properties

  • static – property of the Class
    • Used for utility functions
    • Used for constants
    • Used for “global” like variables (shared by all instances)
  • non-static – property of instances of the class
    • used for behavior of object
    • used for instance data
    • a reasonable default

Access modifiers

Public vs. Private

  • public – part of the “interface” of the object
    • Most methods
    • Almost all constructors
    • accessible from any file/class

Access modifiers

Public vs. Private

  • private – Only part of the “implementation”
    • Hidden from user
    • Essential for making/keeping promises.
    • Some methods
    • almost all attributes
    • accessible only from this file

Note – the rules are enforced at a FILE level

Recommendations for writing classes

Declare:

  • instance variables private after class definition and create public methods to set and access variables
  • constructors public no return type (do not use static)
  • most methods public (do not use static), but private helper methods are often useful

Common Object Methods

We overwrite these:

  • toString()
    • Guaranteed to exist
    • Not Guaranteed to be good.
    • Called automatically in many places
  • equals(Object other)
    • Supposed to check “true” equality
    • Guaranteed to exist
    • Not Guaranteed to be good.

Practice

Imagine you wanted to make a java class representing a date in the Gregorian calendar system (The current most common calendar)

  • What information would you need to build a new date object?
  • What information would a date object need to store internally?
  • How should you be able to manipulate a date object?
  • Does your answer depend on anything?

Key idea

As a designer you have to live in two worlds:

  • “Interface” (how do we use this object)
  • “Implementation” (how do we build this object)

It’s nice when they align, but this isn’t always true

  • attributes are often not part of interface
  • helper functions are often not part of interface
  • many objects have “getter” methods for attributes that don’t exist

Keeping these straight: access modifiers

Exercise

Write a GregorianDate class with the following public methods:

  • getYear()
  • getMonth()
  • getDay()
  • .toString() should return the following format April 13, 1981

Submit your to GregorianDate.java file to gradescope

Solution

public class GregorianDate {
    private int year;
    private int month;
    private int day;
    private static final String[] MONTHS = new String[]{"January", "February",
                                                        "March", "April", "May",
                                                        "June", "July", "August",
                                                        "September", "October", "November",
                                                        "December"};
    
    public GregorianDate(int year, int month, int day) {
        this.year = year;
        this.month = month;
        this.day = day;
    }

    public int getYear() {
        return year;
    }

    public int getMonth() {
        return month;
    }

    public int getDay() {
        return day;
    }

    private String getMonthName() {
        return MONTHS[month-1];
    }

    public String toString() {
        return getMonthName() + " " + day + ", " + year;
    }
}

Encapsulation

An object should hide its internal details

  • This is about debugging and changing
  • The more code with access, the more code you need to check.
  • The more code with access – the more ways to make bugs

Looking back

  • An Object exists when a class is instantiated
  • The existence of a class does not imply an Object of that class exists
  • Method types: constructor, setter, getter, operator, helper
  • What does new do?