Objects

Combining variables and methods

Classes

Classes define a classification of objects that share characteristics.

Characteristics can be data and code.

Also known as variables and methods.

Sample class

public class Student {

  private String name;
  private int age;

  public Student(String name, int age) {
    this.name = name;
    this.age = age;
  }

  public boolean canVote() {
    return age >= 18;
  }
}

Objects

Objects are instances of classes.

Each object has its own set of instance variables.

In this case, each student has their own name and age.

Instance variables

private String name;
private int age;

Just like other variables we’ve used but defined at the top-level of a class rather than inside a method.

Can have a access modifier before the type.

Instance variables are usually private.

The constructor

public Student(String name, int age) {
  this.name = name;
  this.age = age;
}

Like a method but no return type.

And name is the same as the class name.

Its job is to initialize the object.

Methods

public boolean canVote() {
  return age >= 18;
}

public boolean alphabeticallyBefore(Student other) {
  return name.compareTo(other.name) < 0;
}

Non-static methods can refer to the instance variables of the object by just their name.

Methods can also take other arguments.

Can also access instance variables of other object if they are accessible.

Objects

Objects are constructed by calling the constructor with the keyword new.

Student fred = new Student("Fred", 17);
Student wilma = new Student("Wilma", 16);
Student barney = new Student("Barney", 18);

Calling a method on an object

fred.canVote() ⟹ false
wilma.canVote() ⟹ false
barney.canVote() ⟹ true
fred.alphabeticallyBefore(wilma) ⟹ true

Note that the canVote method doesn’t take any arguments.

But the behavior of the method is affected by the data hidden in the object.

Using objects

To use an object you need to know what methods it supports.

Methods are defined by their method signature: the name, the return type, and the types of the arguments.

If you are going to create new instances of a class you need to know what constructors it has and what arguments they take.