MOBI BOOT CAMP CORP. logoLearning Buddy
  • SIGN IN
  • Introduction
  • Unit 0: The First Program
  • Unit 1: Using Objects and Methods
    • Part 1: Fundamentals
    • Part 2: Operations and Documentation
    • Part 3: Objects and Classes
      • Calling Class Methods
      • Math Class
      • Objects: Instances of Classes
      • Object Creation and Storage (Instantiation)
      • Calling Instance Methods
      • Types of Variables
      • Pass by value/reference
      • String Manipulation
      • Unit 1 Part 3 Slides
  • Unit 2: Selection and Iteration
  • Unit 3: Class Creation
  • Unit 4: Data Collections

Unit 1.12: Objects and Classes

Objects and Classes

A class is the formal implementation, or blueprint, of the attributes and behaviors of an object. It defines what data the object holds and what actions it can perform.

The Blueprint Analogy
  • A Class is like a blueprint for a house (the instructions).
  • An Object is like the actual house built from that blueprint (the instance).

An object is a specific instance of a class with defined attributes.

Diagram: Class as a Cookie Cutter, Objects as Cookies

Java Code Equivalent:

Task: Defining a class and creating multiple instances.

// The Class (Cookie Cutter)
public class Cookie {
    String shape;
    
    public Cookie(String shape) {
        this.shape = shape;
    }
}

// Creating The Objects (The Cookies)
Cookie cookie1 = new Cookie("Star");
Cookie cookie2 = new Cookie("Star");
Cookie cookie3 = new Cookie("Star");

Attributes and Behaviors

As introduced in Unit 1.7 (API and Libraries), every object is defined by its attributes and behaviors. When we design our own classes, we define these components to represent real-world entities:

  • Attributes (State): These refer to the data or the current state of an object. Attributes are stored in instance variables.
  • Behaviors: These refer to what instances (objects) of the class can do. Behaviors are defined by methods.

You can create many objects from a single class.

Task: Accessing and modifying attributes of custom objects.

// This class is a blueprint for creating Book objects.
class Book {
    String title;
    String author;
    int price; 
}

public class Bookstore {
    public static void main(String[] args) {
        // 'book1' is an object, or an instance of the Book class.
        Book book1 = new Book();
        book1.title = "Harry Potter and the Sorcerer's Stone";
        book1.author = "J.K. Rowling";
        book1.price = 29;

        System.out.println(book1.title);

        Book book2 = new Book();
        book2.title = "Harry Potter and the Prisoner of Azkaban";
        book2.author = "J.K. Rowling";
        book2.price = 31;

        System.out.println(book2.title);
    }
}

Can you name the attributes and behavior of the Dog class?

Task: Defining attributes and behaviors in a class blueprint.

// A simple blueprint for a Dog object
public class Dog {
    // Attribute: what a Dog has
    String name;

    // Behavior: what a Dog does
    public void bark() {
        System.out.println(name + " says: Woof!");
    }
}

Reference Variables

A variable of a primitive type (like int) holds the actual value directly. However, a variable of a reference type (like Book or String) does not hold the object itself.

Memory References
  • A reference variable stores the "address" of where an object lives in RAM. Copying a reference variable (e.g., a = b) does NOT copy the object; it makes both variables point to the same object.

Instead, it holds a reference, which can be thought of as the memory address where the object is stored.

Task: Copying references between variables.

public class ReferenceExample {
    public static void main(String[] args) {
        // 'book1' does not contain the title and author.
        // It contains the memory address of the Book object.
        Book book1 = new Book(); 
        
        // 'book2' is another reference variable.
        Book book2;
        
        // The assignment operator copies the reference (the address)
        // from book1 into book2. Now both variables point to the
        // exact same Book object in memory.
        book2 = book1;
    }
}

What is happening in RAM?

As you create objects, new space is allocated to store the objects and their instance values. The more objects you create, the more your RAM gets filled with these objects. Each object uniquely identifies one specific book. Now you have successfully implemented OOP concepts in creating books!

The figure below shows the depiction of how objects may occupy the RAM area.

Diagram illustrating how created objects (like Book objects) occupy space in RAM with their instance values.

Why should we use OOP concepts while writing software programs?

To solve mathematical equations, OOP concepts are not that important. However, when you build a sophisticated software platform like Amazon, using OOP concepts while writing programs will make it easier for the entire organization to conduct business. OOP helps in replicating real-world entities in software very easily. A website like Amazon is in principle trying to simulate real-world brick-and-mortar stores in software, and OOP helps do exactly that.

Before you write your software, it is important to first understand the real-world stores. So, what entities constitute the business of a brick-and-mortar store?

Well, here are some types of entities we can think of:

  • Customers who visit the stores
  • Customers pick up a Shopping Cart to hold their items
  • Customers pick up Items to buy and place them in their shopping cart
  • Customers get their items checked out at the counter.

When you replicate this in software, it is always a good idea to abstract your programs exactly like they exist in the real world. This way, everyone in the organization is able to communicate in business terms, whether they are talking about software or the actual business. After all, software programs are written to help the business, and not the other way around. Using OOP concepts helps us write software that replicates the real world!

Every customer who walks into the shop is represented as an Object, and every shopping cart that they pull is also considered another type of Object. Similarly, the items the customer picks up to add to their shopping cart are yet another type of Object.

Almost all large-scale software projects that incorporate OOP principles mimic a real-world business or enterprise.

Object-Oriented Programming (OOP)
  • OOP is a programming paradigm based on the concept of "objects," which can contain data (attributes) and code (behaviors). It is used to model complex real-world systems in an organized way.

OOP was introduced for the very purpose of helping mimic the real world.

Class Hierarchy and Inheritance

Inheritance
  • Inheritance allows one class (the subclass) to inherit the members of another class (the superclass). This promotes code reuse and creates an "IS-A" relationship.

Exclusion Statement: Designing and implementing inheritance relationships are outside the scope of the AP Computer Science A course and exam.

A class hierarchy can be developed by putting common attributes and behaviors of related classes into a single class called a superclass. Classes that extend a superclass, called subclasses, can draw upon the existing attributes and behaviors of the superclass without repeating the code. This creates an "IS-A" inheritance relationship from the subclasses to the superclass.

For example, Car IS-A Vehicle, and Motorcycle IS-A Vehicle. Here, Vehicle is the superclass, and Car and Motorcycle are subclasses.

Example: Vehicle Hierarchy

Let's define a Vehicle superclass with common attributes like brand and year, and a behavior like startEngine().

Class Hierarchy: Vehicle

Task: Implementing a simple class hierarchy.

// Superclass
class Vehicle {
    String brand;
    int year;

    public void startEngine() {
        System.out.println("The engine has started.");
    }
}

Now, we can create more specific Car and Motorcycle subclasses that inherit from Vehicle. They get the brand, year, and startEngine() method for free. They can also have their own unique attributes and methods.

Task: Extending a superclass to create specialized subclasses.

// Subclass Car
class Car extends Vehicle {
    int numberOfDoors;

    public void honk() {
        System.out.println("Beep beep!");
    }
}

// Subclass Motorcycle
class Motorcycle extends Vehicle {
    boolean hasSidecar;

    public void wheelie() {
        System.out.println("Performing a wheelie!");
    }
}

Using the Hierarchy

You can now create objects of the subclasses and use both the inherited and the specific members.

Task: Instantiating and using objects from a class hierarchy.

public class Garage {
    public static void main(String[] args) {
        // Create a Car object
        Car myCar = new Car();
        myCar.brand = "Toyota"; // Inherited from Vehicle
        myCar.year = 2022;      // Inherited from Vehicle
        myCar.numberOfDoors = 4; // Specific to Car

        myCar.startEngine(); // Inherited method
        myCar.honk();        // Specific method

        System.out.println("My car is a " + myCar.year + " " + myCar.brand + " with " + myCar.numberOfDoors + " doors.");

        // Create a Motorcycle object
        Motorcycle myMotorcycle = new Motorcycle();
        myMotorcycle.brand = "Harley-Davidson"; // Inherited
        myMotorcycle.hasSidecar = false;        // Specific

        myMotorcycle.startEngine(); // Inherited method
        myMotorcycle.wheelie();     // Specific method
    }
}

This example shows how inheritance allows for code reuse and the creation of a logical hierarchy. The common logic is centralized in the Vehicle superclass, and the specific logic resides in the Car and Motorcycle subclasses.

The Object Class

All classes in Java are, directly or indirectly, subclasses of the Object class. This means every object in Java inherits the methods of the Object class, such as toString(), equals(), and getClass().

Even if a class is not explicitly declared to extend any other class, it implicitly extends Object.

Example: Inheriting from Object

Consider a simple Student class that does not explicitly extend any other class.

Task: Using inherited methods from the universal Object class.

class Student {
    String name;
    int studentId;
}

public class School {
    public static void main(String[] args) {
        Student student1 = new Student();
        student1.name = "Alice";
        student1.studentId = 12345;

        // The .toString() method is not defined in the Student class.
        // It is inherited from the Object class.
        // By default, it prints the class name and the object's hashcode.
        System.out.println(student1.toString()); 

        // The .getClass() method is also inherited from Object.
        // It returns the runtime class of the object.
        System.out.println("The class of student1 is: " + student1.getClass().getName());
    }
}

When you run this code, you will see output similar to this (the hashcode will vary):

Student@15db9742
The class of student1 is: Student

This demonstrates that even though we never wrote a toString() or getClass() method in our Student class, we can still use them because they are automatically inherited from the Object class.

What is a hash code?

A hash code is a 32-bit signed integer representing the object. It is typically printed in hexadecimal representation. While this hash code is often calculated using the memory location, the Java language specification does not require it. https://docs.oracle.com/javase/7/docs/api/java/lang/Object.html#hashCode()

To keep things simple, we have used this hash code to represent memory in our example above.

Privacy Policy | Terms & Conditions