Creating and Storing Objects

  • OOP (Object-oriented programming): programming style where the user:

    • declares classes

    • create objects from classes

    • write programs with interacting objects

Creating and Storing Objects

  • object: something that can be used in code as an instance variable(state) and a method(behavior).

 

Dog

State (instance variables):

  • String name

  • int age

  • boolean goodDog

Dog

Behavior (methods):

  • speak

  • haveBirthday

 

  • class: the template or blueprint from which an object can be created.

    • defines what data the object will have and its method

    • any class created will use the object’s variables and methods.

      public class ObjectName{

    • //instance variables

    • //default and parameter constructors

    • //accessors and mutators

    • //toString and equals

    • //behaviors
      }

Instance Variables

  • An instance variable: is a variable that defines what data your objects will use.

    • instance var. are private, meaning methods and classes besides the object-creating class can use the variable unless programmed to.

    • While instance variables are declared, they are not given values. The constructors take care of that.

    • instance variables are also global variables, and can be freely used throughout your class.

public class Dog {
private int age;
private String name;
private boolean goodDog;
}

Constructors

  • constructor: when called upon, they create the object by making it public as it saves memory to give values to the instance variables. There is only ONE constructor in a class.

    • Constructors do not return any values; they only make space for memory.

    • Constructors have no parameters/additional actions, hence their empty parentheses

    • Since instance variables are declared out of the constructor, constructors are given the default values for the variables.

      int age = 0; 
      String name = "unknown"; 
      boolean goodDog = false; 

Parameter Constructors

  • parameter constructor: serves a similar purpose as a regular constructor, but uses the memory saved from them to add values to the variables. There can be an UNLIMITED amount of parameter constructors in a class.

    • have parameters that list the instance variable’s identifier and data type.

    • to avoid having similar variable names to the instance variables, the “this” keyword is used.

      public class Dog
      {
         //instance variables here
         //default constructor here
      
         public Dog(String n, int a, boolean g)
         {
       
            name = n;
            age = a;
            goodDog = g;
       
         }
      }
      

Creating Behaviors

  • methods: behaviors objects can have. They can be public or private depending on what classes you want them to use.