Learning Objectives

  • Object oriented programming
  • Objects, classes, and methods
  • Creating classes and methods
  • Declaring methods
  • Calling methods

Object Oriented Programming

  • Organizes software design around objects
  • Compartmentalizes data and functions in such a way that data and the functions that operate on data are bound together

Objects, Classes, and Methods

  • Classes are a template or a blueprint from which objects are created.
  • Objects created under the same class will share common methods and attributes.
  • Objects are instances of a class.
  • Methods, otherwise known as functions, are a set of code that perform a specific task.
  • Example: class fruit contains an object like an apple
  • Class attributes are things that the objects inherit
  • Example: calorie count or quantity
  • Methods of a class could be stored or consumed

Creating Classes and Objects

  • An object is initialized by calling a class constructor
Painter myPainter = new Painter ();
|   Painter myPainter = new Painter ();
cannot find symbol
  symbol:   class Painter

|   Painter myPainter = new Painter ();
cannot find symbol
  symbol:   class Painter

Declaring Methods

  • Access modifier: public, protected, private, or default
  • Return type: No return value would mean void
  • Method name: name of method
  • Parameter list: the list of variables the method will operate on based on what's in the parentheses
  • Exception list: exceptions during runtime
  • Method body: Internal code the method will execute
public int max (int x, int y) // modifier, return type, method name, parameter list
{
    if (x>y) // body of the method
        return x;
    else
        return y;
}

Calling Methods

  • Advantageous because it allows for code reuse and optimization
  • Calling a method looks like this: methodName (parameter1, parameter2);
  • Calling an object's method: objectReference.methodName(parameter 1, parameter 2);

2021 FRQ 1

Part A

public int scoreGuess (String guess)
{
    int count = 0;
    for (int i = 0; i <= secret.length() - guess.length(); i++)
    {
        if (secret.substring (i, i + guess.length()).equals(guess))
        {
            count++;
        }
    }
    return count * guess.length() * guess.length();
}

Part B

public String findBetterGuess( String guess1, String guess2) // defines a method
{
    if (scoreGuess(guess1) > scoreGuess(guess2))
    {
        return guess1;
    }
    if (scoreGuess(guess2) > scoreGuess(guess1))
    {
        return guess2;
    }
    if (guess1.compareTo(guess2) > 0)
    {
        return guess1;
    }
    return guess2;
}