Understanding Classes in OOP

Dec 18, 2024

AP Computer Science A Series: Unit 5 - Writing Classes

Introduction

  • Focus on writing classes and using objects.
  • Object-Oriented Programming (OOP) languages: Java, C++, C#, Python.

Key Concepts

Objects

  • States: Represented by fields in Java.
  • Behaviors: Represented by methods.
  • Example: A dog with states (color, awake status, age) and behaviors (bark, run, eat).

Classes

  • A blueprint or template for an object.
  • Static Methods: Accessible without creating an object; identified by static keyword.
    • Example: rotateWheel or openHood in a car blueprint.
  • Non-static Methods: Require an object to access.
    • Example: turnOnEngine or drive.

Class Variables

  • Also known as static fields.
  • Changing a class variable affects all instances.
    • Example: Changing wheelSize changes it for all cars.

Instance Variables

  • Known as non-static fields.
  • Only have values when an instance is created.
  • Changing instance variables affects only that instance.
    • Example: color or licensePlate.

Methods

Static vs. Non-static

  • Static Methods: Can access class variables.
  • Non-static Methods: Can access both class and instance variables.

Access Modifiers

  • Public: Accessible from inside or outside the class.
  • Private: Accessible only within the class.

Method Declaration

  • Return Type: Can be void or any data type.
  • Method Name: Should be descriptive and in lower camel case.
  • Parameters: Optional; used to pass data to methods.

Getter and Setter Methods

  • Getter: Returns the value of a field.
  • Setter: Sets or updates the value of a field.
  • Example: getStudentId, setStudentId for instance variables.
  • Static getters and setters are used for static fields.

Overloading Methods

  • Same name in the same class, different parameters.
  • Rules:
    • Must have different number or types of parameters.
    • Can have different return types.
    • Can be public or private.
    • Can have different static or non-static values.

Constructors

  • Special type of non-static method to set up a new object.
  • Overloaded Constructors: Different parameter lists.
  • this keyword: Used to refer to current object or call another constructor.

Scope and Lifetime of Variables

  • Scope: Where the variable can be accessed.
  • Lifetime: When the variable is created and destroyed.
  • Local Variables: Exist within methods or blocks.
  • Parameters: Created with method call, scope within method.
  • Class Variables: Static fields, shared across all instances.
  • Instance Variables: Non-static fields, unique to each instance.

Conclusion

  • Understanding static vs. non-static, object behaviors, and variable scope is crucial.
  • Practice with examples to solidify understanding.