Classes

  • Classes are “blueprints” that we use to instantiate objects

Why Do We Need Classes

  • Classes are an essential aspect of OOP
  • Models real world objects but in code

Anatomy of a Class

  • Object
    • State, attributes, behavior
    • Instance of a class
    • Represented by an instance in the program
  • Class
    • Defines an abstract data type
    • Object references
      • String variables
    • Instance Variables
      • Attributes, behaviors
      • Data for objects ### Methods and Constructors
  • Methods
    • Behaviors or actions that apply to the objects
  • Behaviors or actions that apply to the objects
    • Creates the object

Main Method

  • Tests the class
  • Instance variables
    • Attributes, fields, properties

Constructors

  • Special method for object instantiation
    • Sets initial values for variables
    • Can run methods
  • Default Constructor
    • No constructor defined
    • No arguments
  • Can have multiple constructors per class

Documentation with Comments

  • Comment with // for a single line
  • / / for multiple line
  • /* / for documentation comment
  • Help with explaining what code is about
  • Preconditions
    • What must be true before code is implemented
  • Postconditions
    • Should be true after method is run
    • Describe the output if the method

Accessor & Mutator Methods

  • Get of methods or getters
    • Allows you to ‘get’ values of variables
    • Returns a copy of variable
  • Non-Void Methods
    • Return a value of specified data type
    • No parameters

Mutator Methods

  • Set of methods or setters
    • Allows you to change the values of instance variables
  • Void methods
    • Will not return a value
    • Will take parameters for instance variables

Writing Methods

  • 3 Parts:
    • Method Definition (Modifiers, Return Type)
    • Method Signature (Name, Parameters)
    • Method Body (Code)
  • camelCase
  • Object.method()

Method Return Types

  • String
    • Returns a string
  • Int
    • Returns an integer
  • Bool
    • Returns a Boolean
  • Any Object Type
    • Returns specified Object
  • Void
    • Method have any return values

Keywords in Java

  • Key word usually used after access modifiers
  • Denotes as belonging to a class
  • Objects cannot reference/use static variables & methods
  • Universally shared variables and methods among objects

This

  • Refers to the constructor that it is being called in
  • Eliminates confusion between attributes and parameters

Access Modifiers

  • Restricts scope of classes, variables, and functions
  • Mainly used for encapsulation
  • Prevents misuse of data & methods

Scope and Access

  • Where a variable can be accessed or used
    • Declaration of variable
  • 3 Levels:
    • Class Level: Instance var
    • Method Level: Local, Parameter var
    • Block Level: Loops, If/Else