Exam Study Notes: Classes and Objects

Classes and Objects

  • Most programs manipulate things called objects, which combine data and operations.
  • Objects can represent real-world items.
  • Object-oriented programming languages represents objects as variables.

Objects

  • An object is the core element that programs create and manipulate.
  • It comprises a thing and the operations that act upon it.
  • Example: A four-digit code number for a photocopy machine.
    • Object: The four-digit code number.
    • Operations: readNumber, getSeparateDigits, testValidity, and writeNumber.
  • A program may involve multiple types of objects.
  • Example: A library database program.
    • Book object: Manipulated by getTitle, getAuthor, isOnShelf, isFiction, and goOutOfPrint.
    • ListOfBooks object: Manipulated by search, addBook, removeBook, and sortByAuthor.
  • Objects are defined by:
    • State (attributes): Characteristics such as title and author.
    • Behavior: Actions that the object can perform, such as going out of print.
  • An object is a concept independent of specific programming languages.
  • Java uses object references to represent objects as variables.

Classes

  • A class serves as a blueprint for creating objects of a particular type.
  • An object is a single instance of a class.
  • The state of an object is stored in data fields (instance variables) of the class.
  • The class methods define the object's behavior and operations.
  • Data encapsulation: Combining an object's data and methods into a class.

Public, Private, and Static

  • public: The class is usable by all client programs (code outside the class).
    • In AP Java, all classes are public.
  • Public methods are accessible to all client programs.
  • Client programs should not access private instance variables or methods.
  • private: Restricts access.
    • Private methods and variables can only be accessed by methods within the same class.
    • In AP Java, instance variables are private.
  • static: A static variable (class variable) is shared by all instances of the class; memory allocation happens once.
    • Typical uses: tracking statistics, accumulating totals, providing unique ID numbers.
    • Static final variables (constants) cannot be changed; often declared public (e.g., Math class constants).
    • A client accesses a static variable using ClassName.VARIABLE_NAME; within the class, it is referred to as VARIABLE_NAME.

Methods Headers

  • The general form for method headers (excluding constructors and static methods) is:
    • accessSpecifier returnType methodName(parameterList)
    • Access specifier: Determines method accessibility.
    • Return type: void indicates no return value.
    • Parameter list: Comma-separated items, each with a data type.
  • The implementation of the method, enclosed in a {} block, follows the header.

Types of Methods

Constructors

  • Constructors create objects of a class, sharing the same name as the class and having no return type.

  • Multiple constructors allow for different object initialization methods.

  • No-argument constructor: Provides default initial values.

    • Example: BankAccount b = new BankAccount(); initializes a BankAccount object with a zero balance and an empty string password.
    • The new operator returns the address of the new object, which is assigned to the object variable (reference).
  • Constructor with parameters:

    • Sets instance variables to specified values upon object creation.
    • Example: BankAccount c = new BankAccount("KevinC", 800.00);
    • b and c are object variables that hold the memory addresses (references) of their BankAccount objects.

Accessors

  • Accessors are public methods that access an object's state without modifying it, returning information about the object.
  • They allow access to private instance variables.
  • Example:
    public double getBalance(){
    return balance;
    }
  • Dot operator: The . operator indicates that getBalance() is a method of the BankAccount class.
  • Non-void methods return a single value, specified in the method header.

Mutators

  • Mutators change the state of an object by modifying instance variables.
  • These methods are frequently void.
  • Mutators can be private helper methods or public methods.

Static Methods

  • Static methods perform operations for the entire class, not individual objects.

  • They are declared using the static keyword in their header.

  • Static methods cannot directly call instance methods or access private instance variables because there's no implied object.

  • They can use static variables.

  • Example: A static method to get the employee count in an Employee class.
    public static int getEmployeeCount() { return employeeCount; }

  • Example: A static method to retrieve the interest rate for all bank accounts.

  • Instance methods are called using an object variable (e.g., object.method()).

  • Static methods are called using the class name (e.g., ClassName.method()).

  • Driver Class:

    • main method
  • Static methods within a driver class containing main() must be static.

  • The main() method needs to be static since, at the start of program execution, no objects exist yet.

Method Overloading

  • Method overloading involves two or more methods in the same class (or a subclass) with the same name but different parameter lists.
  • The compiler determines which method to call based on the method's signature (name and parameter types).
  • Return type is irrelevant for overloading purposes.
  • Overloaded constructors allow various object initialization methods.

Scope

  • The scope of a variable or method refers to the region where it is visible and accessible.
  • Class scope: Instance variables, static variables, and methods are accessible throughout the class (from the opening brace to the closing brace).
  • Local variable: Defined inside a method or a statement; its scope extends from its declaration point to the end of the enclosing block ({}).
  • Local variables take precedence over instance variables with the same name.

The this Keyword

  • this refers to the implicit parameter (the object for which the method is called) within an instance method.
  • Within instance methods, instance variables can be written with the this prefix (e.g., this.variableName).
  • Explicit and Implicit Parameters:
    • In a method call obj.doSomething("Mary", num), "Mary" and num are explicit parameters, while obj is the implicit parameter.
  • Examples of Using this:
    • To print the current object in the printPerson method: System.out.println(this); (invokes the toString method).
    • To differentiate between instance variables and parameters with the same name in a constructor:
      this.num
      this.denom

References

  • Reference vs. Primitive Data Types:

    • Primitive data types: double, int, char, boolean.
    • Reference data types: objects and arrays (e.g., String, Random, int[], String[][], custom classes).
    • Primitive variables directly store values; reference variables store memory addresses.
  • Declaration of objects:
    Date d = new Date(2, 17, 1948);
    * This creates a reference variable d that refers to a Date object. The value of d is the address in memory of that object

  • Aliasing: Having two references to the same object.

    • Example:
      Date birthday = d;

    • Changes made through one reference affect the other.

    • Null Reference

    • You can test whether a variable refers to an object or is uninitialized by using the keyword null

    • Example:
      if (b == null)

    • The declaration BankAccount b; defines a reference b that is uninitialized. This is known as uninitialized object variable or a null reference/pointer.

  • If a reference is not null, it can be set to null with the statement b = null;

  • Compile-time vs Run-time errors:

    • Failing to initialize a local variable results in a compile-time error.
    • Failing to initialize an instance variable results in a run-time error (NullPointerException).
    • Do not make a method call with an object whose value is null.

Method Parameters

  • Formal vs. Actual Parameters:

    • Formal parameters: Placeholders in the method header (e.g., acctPassword and amount in withdraw(String acctPassword, double amount)).
    • Actual parameters: Values supplied during the method call (e.g., "TimB" and 250 in b.withdraw("TimB", 250)).
  • Passing Primitive Types as Parameters

    • Parameters are passed by value; a copy of the argument's value is created in a new memory slot.
    • Changes to parameters within the method do not affect the original arguments.
  • Passing Objects as Parameters

  • In Java both primitive types and object references are passed by value

    • The key difference is that the address (reference) is copied, not the values of the individual instance variables.
    • Changes to the parameter within the method do affect the original object.
  • The reference is unchanged throughout, however any value associated is changed.

  • Returning an object from a method means that you are returning the address of the object (does not create a new object).