Module 1: Classes, Objects, and Access

Module Overview

Learn about fundamental object-oriented programming concepts in Java, including classes, objects, and access modifiers.

Learning Objectives

  • Define instance variables to store the internal state of an object
  • Implement a class with multiple constructors to allow optional constructor arguments
  • Explain the relationship between a class and an object
  • Implement code to instantiate an object by calling a constructor with and without parameters
  • Declare variables of the correct types to store referenced objects
  • Explain the scope of visibility of a class's public and private member variables
  • Implement code to call an instance method and use its returned value
  • Implement code to call an instance method that has a void return type
  • Recall that calling a method executes the statements in the method before continuing
  • Define the behavior of an object through a method written in the class
  • Implement an instance method that reads the value of one of its class's instance variables
  • Implement an instance method that modifies the value of one of its class's instance variables
  • Implement an instance method with a reference to the current object using the keyword, "this"
  • Explain the scope of visibility of a local variable declared at the top of a method
  • Explain the scope of visibility of a local variable declared within a code block
  • Explain the scope of visibility of a method parameter variable

Key Concepts Explained

Classes are templates for creating objects. They define the structure and behavior that the objects will have.

Instance Variables

Instance variables store the state of an object. Each object created from a class has its own copy of these variables.

public class Person {
    // Instance variables
    private String name;
    private int age;
}

Constructors

Constructors initialize objects when they are created. You can have multiple constructors to provide different ways to create objects.

public class Person {
    private String name;
    private int age;
    
    // Default constructor
    public Person() {
        this.name = "Unknown";
        this.age = 0;
    }
    
    // Parameterized constructor
    public Person(String name, int age) {
        this.name = name;
        this.age = age;
    }
}

Access Modifiers

Access modifiers control the visibility of class members (variables and methods).

  • private: Accessible only within the same class
  • public: Accessible from any class
  • protected: Accessible within the same package and subclasses
  • default: Accessible only within the same package

Object Instantiation

Creating an object from a class is called instantiation. You use the "new" keyword followed by a constructor call.

// Creating objects
Person person1 = new Person(); // Using default constructor
Person person2 = new Person("John", 25); // Using parameterized constructor

Instance Methods

Instance methods define the behavior of objects. They can access and modify the object's state.

public class Person {
    private String name;
    private int age;
    
    // Constructor
    public Person(String name, int age) {
        this.name = name;
        this.age = age;
    }
    
    // Instance method that returns a value
    public String getName() {
        return this.name;
    }
    
    // Instance method that modifies state
    public void setAge(int age) {
        this.age = age;
    }
    
    // Instance method with void return type
    public void greet() {
        System.out.println("Hello, my name is " + this.name);
    }
}

Common Patterns and Best Practices

Encapsulation

One of the key principles of OOP is encapsulation - hiding the internal state of an object and requiring all interaction to be performed through well-defined methods.

// Good encapsulation
public class BankAccount {
    private double balance; // Private instance variable
    
    public double getBalance() {
        return balance;
    }
    
    public void deposit(double amount) {
        if (amount > 0) {
            balance += amount;
        }
    }
    
    public boolean withdraw(double amount) {
        if (amount > 0 && balance >= amount) {
            balance -= amount;
            return true;
        }
        return false;
    }
}

Object Composition

Building complex objects by combining simpler ones is a powerful design technique.

public class Address {
    private String street;
    private String city;
    private String zipCode;
    
    // Constructor, getters, and setters
}

public class Person {
    private String name;
    private Address address; // Object composition
    
    // Constructor, getters, and setters
}

Additional Resources

Practice Exercises

Complete these exercises to reinforce your understanding of classes, objects, and access modifiers.

Exercise 1: Create a Car Class

Create a Car class with the following features:

  • Private instance variables for make, model, year, and fuelLevel
  • Multiple constructors (default and parameterized)
  • Methods to drive (decreases fuel level) and refuel (increases fuel level)
  • Getters and setters for all instance variables

Exercise 2: Bank Account Management

Create a BankAccount class with:

  • Private instance variables for accountNumber, balance, and owner
  • Methods for deposit, withdraw, and transfer
  • Appropriate validation to ensure balance doesn't go negative

Guided Projects

Complete these exercises to reinforce your understanding of classes, objects, and access modifiers.

Mastery Task 4 - Constructing Classes

Mastery Task Guidelines

Mastery Tasks are opportunities to test your knowledge and understanding through code. When a mastery task is shown in a module, it means that we've covered all the concepts that you need to complete that task. You will want to make sure you finish them by the end of the week to stay on track and complete the unit.

Each mastery task must pass 100% of the automated tests and code styling checks to pass each unit. Your code must be your own. If you have any questions, feel free to reach out for support.

AppSettings Update

Go to com.adventure.settings.AppSettings and update the story to MT4_HouseAndCave.

Constructors

Constructors allow us to instantiate (i.e. make a concrete object of) a class. In our game, we have keys and doors. The class files for these objects are mostly built out, but they are missing their constructors and some important properties.

Working Classes

We will be working with the following classes:

  • Key - adventure.world.objects.keys.Key
  • KeyFactory - adventure.world.objects.keys.KeyFactory
  • Door - adventure.world.objects.doors.Door
  • DoorFactory - adventure.world.objects.doors.DoorFactory

Creating a Key

Open the Key class where you'll add two properties and two constructors.

The properties you'll need are

  • level (int)
  • name (String)

Once these are in place, you can create two constructors.

  • The first constructor will take no parameters and will set the level and name to default values 1 and "key", respectively.
  • The second constructor will require the level. You will save the level to its respective property. Set the name to "key".
  • The third constructor will require two parameters that will represent the level and name. You will save these parameters to their respective properties in the Key class.

You'll need to update some code in the Key class after you add the properties to make the class work properly. Read the comments inside the Key class for instructions on how you should edit the code.

KeyFactory

A factory is a class that builds instances of another class (or classes). You can read more on factories later, but for now, open the KeyFactory class and update the buildKey method to leverage your new two-parameter Key constructor.

Creating a Door

In the Door class, you'll take similar steps as with the Key class and add one property and two constructors.

The property you'll need to add is level (int).

Once level is in place, you can create two constructors. The first will take no parameters and will set the level and isOpen (isOpen already exists) to default values 1 and false, respectively. The second constructor will require two parameters that will allow a custom level and isOpen values. These parameters should be saved to their respective properties.

Like the Key class, you'll need to update some code in the Door class once these properties are added to make the class works properly. Read the comments for where you should edit the code.

Another Factory

Open the DoorFactory class and update the buildDoor method to leverage your new Door constructor.

Testing

To run the tests for this assignment, run the following:

./gradlew test --tests com.adventure.MT4

or by right-clicking the MT4 file and selecting "Run 'MT4'"

You can check your code styling by running the linter with the following command:

./gradlew checkstyleMain

You can run the game by going to the Main class and clicking on the run icon to the left of the main() method.