Classes, Instance Variables, Constructors, and Methods

Instance Variables

  • Also known as properties or fields.
  • Belong to an instance (object) of a class.
  • Differ from local variables, which exist only inside a method.
  • Declared within the class, typically right below the class header.
  • Scope: entire class.
  • Should be declared as private.
  • Initialized in the constructor.
  • Store the defining properties of an object.

Constructors

  • Special code block run when a new object of the class is created.
  • Looks like a method but is technically not.
  • Typically public.
  • No return type (not even void).
  • Must have the same name as the class.
  • Job: initialize instance variables of the object.
  • Initializes the class’ fields (instance variables) and creates a new object in memory.
  • When you see the new keyword, it means a class’ constructor is being called to create a new object.

Methods

  • Instance method: A non-static method written inside a class.
  • Belongs to every instance (object) the class produces.
  • Absence of the static keyword means only objects can run the method.

Multiple Constructors

  • Possible and useful to have multiple constructors in a class.
  • Allows object creation based on available information.
  • Default constructor: Constructor with no parameters; initializes instance variables to default values.
    • Example: public Cat()
  • Secondary constructor: Also called a "parameterized" constructor because it has parameters; initializes instance variables to the values of the supplied parameters.
    • Example: public Cat(String n, String b)
  • Method overloading: Having more than one method with the same name but different parameters (in type and/or number).
    • Constructors can be overloaded like regular methods.

Example Scenario: BankAccount Class

public class BankAccount {
    double balance; //instance variable

    public BankAccount() //default constructor
    {
        balance = 0; //initializes the instance variable to 0
    }
    public BankAccount(double bal) //secondary constructor
    {
        balance = bal; //assign balance the same value as bal
    }
}