Defining classes

  • Fields are variables that hold the data stored in objects, also known as instance variables.

  • Constructor. The default constructor goes away even if you write your own constructor that takes parameters, so you must define both explicitly.

  • this keyword. A method invocation implicitly passes an object as a parameter called this.

  • static keyword. A static field is a single variable that shared by a whole class of objects; its value does not vary from object to object, also known as class variables.

    • call it by class name
    • eg. System.in
int kids = Human.numberOfHumans / 4;
  • A static method doesn't implicitly pass an object as a parameter.

    • It lets a method run without any instance of the class.
    • Cannot use non-static (instance) variables / methods.
    • The main() method is always static, because when we run a program, we are not passing an object in.
  • Initializing a static variable

    • Static variables in a class are initialized before any object of that class can be created.
    • Static variables in a class are initialized before any static method of the class runs.

Lifetimes of Variables

  • A class variable (static field) lasts as long as the program runs.

HFJ Reading

  • A class describes what an object knows and what an object does.
  • A method uses parameters. A caller passes arguments.
  • Java is pass-by-value.
  • Instance variable vs. local variable
    • Local variables do NOT get a default value.

results matching ""

    No results matching ""