Java Classes and Objects

CSCI 1933 – Introduction to Algorithms and Data Structures
Adriana Picoral

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());
    }
}

Access Modifiers

For now, you have used public and private:

  • public - accessible from anywhere in the program, by any class in any package.
  • private - accessible only within the same class. This is the most restrictive modifier.

We will take more about these later:

  • protected - accessible within the same package AND by subclasses in other packages.
  • default/package-private (no modifier) - Accessible only within the same package.

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?