Lesson 3

Classes and Methods

Lesson Outcomes

Today we’ll be expanding on Java’s capabilities by introducing its object-oriented features.

By The end of this lesson you should:

  • Understand the difference between classes and objects
  • Have created your own classes
  • Have created and used methods on your classes, that use the class' internal state
Classes

So far we've used Java's provided types (e.g. String, Integer).

Now we will create our own objects to represent things that exist in our world

What if I want to represent a Person, who has a name, age and height?

We can do this in Java be defining a class - a blueprint from which we can create many Persons:


public class Person {
  private String name;
  private Integer age;
  private Integer height;

  public Person(String name, Integer age, Integer height) {
    this.name = name;
    this.age = age;
    this.height = height;
  }

  public String getName() {
    return name;
  }

  public Integer getAge() {
    return age;
  }

  public Integer getHeight() {
    return height;
  }
}
          

There's a few things going on, so we'll cover these step-by-step


public class Person {
...
}
        

This defines that we’re creating a new blueprint/class which defines a Person - it is public meaning anyone anywhere in another file can use this class.


public class Person {
  private String name;
  private Integer age;
  private Integer height;
  ...
}
        

A field/property is a variable that belongs to the class - they are the internal state of the class.

In this case name, age and height are the state of a Person.

These properties are private to stop outside access and editing in ways we don't want.

Notice that we now cannot use var for properties.


public class Person {
  // fields/properties
  public Person(String name, Integer age, Integer height) {
      this.name = name;
      this.age = age;
      this.height = height;
  }
  ...
}
        

A constructor is the method used to create new Persons.

This method creates a new instance of Person and then lets us define what to do with the new instance

In this case name, age and height are initialized from the arguments of the same name.

Notice that we now cannot use var for arguments.

Methods

public class Person {
  this.name = name;
  // other fields/properties
  // constructor
  public String getName() {
      return name;
  }
  // other methods
}
          

methods use the internal state of the object to return a result.

Methods are the only way you'll interact with objects, this lets the creator know that the internal state is always valid.

Exercises

Classes and Methods

click here for the exercise sheet