Getting Started
As programs grow more complex, managing all the code in a single, long file becomes difficult and error-prone. To solve this, object-oriented programming provides a way to organize code by modeling real-world or conceptual things. We create "blueprints" called classes that define the properties and actions of these things, allowing us to build organized, reusable, and maintainable software.
What You Should Be Able to Do
Define the relationship between a class (a blueprint) and an object (an instance).
Identify the main components of a Java class: instance variables, constructors, and methods.
Explain that a Java program is a collection of classes and that execution begins in the
mainmethod.Describe how an object's "state" is stored in instance variables and its "behaviors" are defined by methods.
For a given problem, identify the necessary classes, properties (state), and actions (behaviors) required to model a solution.
Key Concepts & Java Implementation
The Core Idea
In Java, the fundamental unit of organization is the class. A class is a blueprint used to create objects. Think of a Car class as the set of architectural plans for a car. It defines what all cars will have (e.g., a color, a speed) and what all cars can do (e.g., start engine, accelerate).
An object is a specific instance created from that class blueprint. While the Car class is the plan, a red sedan with license plate "JAVA-123" is an actual object, or instance, of that class. Another object could be a blue SUV with a different license plate. Each object is distinct, but they both follow the rules defined in the Car class.
A class defines two key things for its objects:
State: The properties or data that an object maintains. This is stored in instance variables. For a
Carobject, the state might include its color, current speed, and fuel level. Each object has its own set of instance variables.Behavior: The actions that an object can perform. These are defined by the class's methods. For a
Carobject, behaviors could includestartEngine()oraccelerate().
A complete Java program is a collection of one or more classes that work together. To run the program, one of these classes must contain a special method called main, which serves as the program's entry point.
Syntax & Implementation
Let's model a simple Student class and a School class to run our program. This demonstrates how two classes collaborate.
Annotated Java Examples
The
StudentClass (The Blueprint)This class defines what a
Studentis. It doesn't run on its own; it's a template for creatingStudentobjects.// The class keyword starts the blueprint definition for a Student. public class Student { // Instance variables define the "state" of each Student object. // Each Student object gets its own copy of these variables. private String name; private int gradeLevel; private double gpa; // The constructor is a special method for creating and initializing a new object. // It has the same name as the class and no return type. public Student(String studentName, int studentGrade) { this.name = studentName; this.gradeLevel = studentGrade; this.gpa = 0.0; // A default value for a new student. } // Methods define the "behaviors" of a Student object. // This method allows a student to update their GPA. public void updateGpa(double newGpa) { this.gpa = newGpa; } // This method allows us to get information about the student's state. public void displayInfo() { System.out.println("Name: " + this.name + ", Grade: " + this.gradeLevel); } }The
SchoolClass (The Runner)This class contains the
mainmethod. Its job is to start the program and use theStudentblueprint to create and manageStudentobjects.// A separate class that will contain the main method. public class School { // The main method is the entry point for the entire program's execution. public static void main(String[] args) { // The 'new' keyword creates an object, or an instance of a class. // 'student1' is an object of type Student. Student student1 = new Student("Alice", 10); // 'student2' is a second, completely separate object of type Student. Student student2 = new Student("Bob", 11); // We can call methods (behaviors) on our objects. student1.updateGpa(3.8); student2.updateGpa(3.5); // Calling a method on each object shows their distinct states. student1.displayInfo(); // Prints info for Alice student2.displayInfo(); // Prints info for Bob } }
Tracing & Analysis
Execution Trace
Let's trace the state of the objects created in the School class's main method.
Line of Code in main | student1 State (name, gradeLevel, gpa) | student2 State (name, gradeLevel, gpa) | Console Output |
|---|---|---|---|
Student student1 = new Student("Alice", 10); | name: "Alice", gradeLevel: 10, gpa: 0.0 | (not yet created) | |
Student student2 = new Student("Bob", 11); | name: "Alice", gradeLevel: 10, gpa: 0.0 | name: "Bob", gradeLevel: 11, gpa: 0.0 | |
student1.updateGpa(3.8); | name: "Alice", gradeLevel: 10, gpa: 3.8 | name: "Bob", gradeLevel: 11, gpa: 0.0 | |
student2.updateGpa(3.5); | name: "Alice", gradeLevel: 10, gpa: 3.8 | name: "Bob", gradeLevel: 11, gpa: 3.5 | |
student1.displayInfo(); | (unchanged) | (unchanged) | Name: Alice, Grade: 10 |
student2.displayInfo(); | (unchanged) | (unchanged) | Name: Bob, Grade: 11 |
Analysis
Notice that calling updateGpa on student1 only changed the gpa instance variable for that specific object. The state of student2 was completely unaffected. This separation of state is a core benefit of object-oriented design. By defining a Student class, we can create as many independent Student objects as we need, each managing its own data.
Java Syntax Quick-Reference
class: The keyword used to define a new class, which acts as a blueprint for objects.public static void main(String[] args): The exact signature for themainmethod, which serves as the starting point for a Java program's execution.new: The keyword used to instantiate (create) a new object from a class.
Core Code Examples & Terminology
Class: A template or blueprint that defines the properties (instance variables) and behaviors (methods) for a type of object.
Object: A specific instance of a class, with its own state and access to the class's behaviors. Also called an instance.
Instance Variable: A variable defined within a class for which each instantiated object has its own separate copy. Instance variables represent the state of an object.
Method: A block of code within a class that defines a behavior or action an object can perform.
Constructor: A special method that is called when an object is created with the
newkeyword. It is used to initialize the object's instance variables.State: The collective data stored in an object's instance variables at any given time.
Behavior: The set of actions an object can perform, as defined by its public methods.
Core Snippet 1 (Class Definition): A minimal class structure defining a blueprint.
public class Book { private String title; // Instance variable for state // Constructor and methods would go here... }This code defines a blueprint for
Bookobjects, each of which will have atitle.Core Snippet 2 (Object Instantiation): Creating an object from a class in a
mainmethod.public class Library { public static void main(String[] args) { Book myBook = new Book(); // Creates a Book object } }This code uses the
newkeyword to create a specificBookobject namedmyBook.
Core Skill Check
Code Tracing: What is printed by the final line of this Java code?
// In a Player class: public int score = 0; Player p1 = new Player(); Player p2 = new Player(); p1.score = 100; System.out.println(p2.score);Answer:
0Debugging: Identify the conceptual error in this Java code.
// The Dog class has a 'public void bark()' method. public class Park { public static void main(String[] args) { Dog.bark(); // Error is on this line } }Answer: The error is calling the
bark()method on theDogclass itself. Methods (behaviors) must be called on a specific object (e.g.,Dog myDog = new Dog(); myDog.bark();).Application: Write a single line of Java code that creates an object of the
Rectangleclass and assigns it to a variable namedbox.Answer:
Rectangle box = new Rectangle();
Common Misconceptions & Errors
Confusing a Class with an Object: A class is the recipe; an object is the cake you bake from it. You cannot interact with the class directly (e.g.,
Student.updateGpa()). You must first create an object (Student s1 = new Student()) and then call methods on that object (s1.updateGpa()).Believing a Program is Only One Class: While simple programs can be written in one file, any meaningful Java application is a collection of multiple classes working together (e.g., a
Studentclass and aSchoolclass).Forgetting Each Object Has Its Own State: If you create two
Carobjects,carAandcarB, changing the color ofcarAhas no effect on the color ofcarB. Each object's instance variables are independent.Thinking All Code Must Go in
main: Themainmethod is only the starting point. The goal of good design is to place behaviors (methods) in the class that is responsible for them, and then havemaincoordinate the creation of objects and the calls to their methods.
Summary
Good program design in Java is built on the relationship between classes and objects. A class serves as a blueprint, defining the state (through instance variables) and behaviors (through methods) for a category of things. Objects are the individual, concrete instances created from that blueprint, each maintaining its own unique state. A complete program consists of one or more classes, and execution always begins in the main method of a designated class. This object-oriented approach allows programmers to build complex systems from simple, reusable, and well-organized components.