AP Computer Science A

Advanced Placement Computer Science A focusing on Java programming and object-oriented design.

Advanced Topics

Object-Oriented Programming: Classes and Objects

Building with Objects: The Heart of Java

Java is an object-oriented language, which means you organize your code around real-world things called objects. Each object comes from a class, which is like a blueprint.

Defining a Class

A class defines the properties (fields) and behaviors (methods) of an object.

public class Dog {
  String name;
  int age;
  
  void bark() {
    System.out.println(name + " says woof!");
  }
}

Creating Objects

Dog myDog = new Dog();
myDog.name = "Buddy";
myDog.age = 3;
myDog.bark(); // Output: Buddy says woof!

Why Use OOP?

  • Organize code to match real-world ideas.
  • Make programs easier to build and understand.
  • Reuse code by creating multiple objects from the same class.

Real-World Examples

  • A Car class for a racing game, each with different colors and speeds.
  • A Student class for a school system, tracking names, grades, and ID numbers.

Examples

  • Designing a Book class for a library app.

  • Creating a Circle class to calculate area and circumference.

In a Nutshell

Object-oriented programming helps you model the real world using classes and objects in Java.

Key Terms

Object
An instance of a class with its own data and behaviors.
Field
A variable inside a class representing a property.
Method
A function inside a class defining an action.