OOP

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

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

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

Practice

Not a good way to do this:

First.java

public class First {
    public int x = 7; 
    public int y = 3; 
}

UseFirst.java

public class UseFirst {
    public static void main(String[] args) {
        First firstOne = new First();
        System.out.println(firstOne.x);
        System.out.println(firstOne.y);
    }
}

Practice

Add static after public for one of the instance variable (to make it a class variable). What is the side effect?

First.java

public class First {
    public int x = 7; 
    public int y = 3; 
}

UseFirst.java

public class UseFirst {
    public static void main(String[] args) {
        First firstOne = new First();
        firstOne.x = 0;
        First firstTwo = new First();
        System.out.println(firstOne.x);
        System.out.println(firstOne.y);
        System.out.println(firstTwo);
        System.out.println(firstTwo);
    }
}

Common Object Methods

We write these:

  • getters: getSomething( )
    • direct access to the state of the object
    • (Not the same as direct access to instance-variables)
  • setters: setSomething(<type> newVal)
    • request modification of state
    • (no promise that modification will happen)
    • (not the same as direct modification to instance variable)

Constructors

Same name as the class, no return type

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

A better example

public class First {
    private int x = 7;
    private int y = 3;
    
    // constructor
    public First(int x, int y) {
      this.x = x;
      this.y = y;
    }
    
    // setters
    public void setX(int x) {
        this.x = x;
    }

    public void setY(int y) {
        this.y = y;
    }
    
    // getters
    public int getX() {
        return x;
    }
    
    public int getY() {
        return y;
    }

}

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 to gradescope: https://www.gradescope.com/courses/1074753/assignments/7004597

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