Getting Started
In programming, we often need to represent complex, real-world entities like students, bank accounts, or cars. While primitive types like int and boolean are useful for storing single pieces of data, they can't capture the structure and behavior of such entities. Object-Oriented Programming solves this by allowing us to define our own custom data types using classes, which act as blueprints for creating individual objects.
What You Should Be Able to Do
Explain the relationship between a class and an object using the "blueprint" and "instance" analogy.
Use the
newkeyword to create an object from a class.Identify and call a class's constructor to initialize a new object's state.
Create multiple, distinct objects from a single class definition.
Differentiate between an object reference and the object itself.
Key Concepts & Java Implementation
The Core Idea
In Java, a class is a blueprint or template for creating objects. It defines a set of properties (attributes) and behaviors (methods) that all objects of that type will have. For example, a Dog class might define attributes like name and breed, and behaviors like bark().
An object is a specific instance of a class. While the class is the abstract blueprint, an object is a concrete entity created from that blueprint that exists in the computer's memory. Using our Dog class blueprint, we could create many individual Dog objects: one named "Fido" of breed "Golden Retriever" and another named "Lucy" of breed "Poodle". Each object has its own set of attributes but shares the same behaviors defined by the class.
To create an object, we must perform two steps: declaration and instantiation. Declaration creates a variable to hold a reference to the object, while instantiation uses the new keyword to actually create the object in memory and a special method called a constructor to set its initial state. A constructor is a block of code that initializes a newly created object; it often accepts parameters to set the initial values of the object's instance variables.
Syntax & Implementation
The process of creating an object is called instantiation. This is done by calling a constructor of the class using the new keyword.
- Syntax Table
| Component | Purpose | Java Example |
|---|---|---|
new | A Java keyword that allocates memory for a new object. | new Dog("Fido", "Retriever"); |
Constructor Call | A call to a special method that has the same name as the class. It initializes the new object's state. | Dog("Fido", "Retriever") |
Object Creation | The complete statement that declares a reference variable and assigns a new object to it. | Dog myDog = new Dog("Fido", "Retriever"); |
- Annotated Java Examples
First, let's define a simple Student class. This class acts as our blueprint.
// Student.java
// This class is the blueprint for creating Student objects.
public class Student {
// Instance variables (attributes) for each Student object
private String name;
private int studentID;
private double gpa;
// This is the constructor. It has the same name as the class.
// It runs when a new Student object is created.
public Student(String studentName, int id, double initialGpa) {
// 'this.name' refers to the instance variable.
// 'studentName' is the parameter passed to the constructor.
this.name = studentName;
// Initialize the other instance variables.
this.studentID = id;
this.gpa = initialGpa;
}
// A simple method to display student info
public void displayInfo() {
System.out.println("Name: " + this.name + ", ID: " + this.studentID);
}
}
Now, in another file with a main method, we can create and use instances (objects) of our Student class.
// School.java
// This class demonstrates the creation and use of Student objects.
public class School {
public static void main(String[] args) {
// 1. Declare a reference variable 'student1' of type Student.
// 2. Use the 'new' keyword to create a new Student object in memory.
// 3. Call the Student constructor, passing in arguments to initialize it.
Student student1 = new Student("Alice", 101, 3.8);
// Create a second, completely separate Student object.
// 'student2' refers to a different object in memory than 'student1'.
Student student2 = new Student("Bob", 102, 3.5);
// Call a method on each object.
// Each object has its own data, so the output will be different.
System.out.println("First student's info:");
student1.displayInfo(); // Output: Name: Alice, ID: 101
System.out.println("\nSecond student's info:");
student2.displayInfo(); // Output: Name: Bob, ID: 102
}
}
Tracing & Analysis
- Execution Trace
Let's trace the creation of the two Student objects in the School.java file.
Student student1 = new Student("Alice", 101, 3.8);Java declares a variable named
student1that can hold a reference to aStudentobject.The
newkeyword allocates a new block of memory for aStudentobject.The
Studentconstructor is called with"Alice",101, and3.8.Inside the new object,
nameis set to"Alice",studentIDis set to101, andgpais set to3.8.The memory address of this new object is assigned to the
student1variable.
Student student2 = new Student("Bob", 102, 3.5);Java declares a second variable named
student2.The
newkeyword allocates another, completely separate block of memory for aStudentobject.The
Studentconstructor is called with"Bob",102, and3.5.Inside this second object,
nameis set to"Bob",studentIDis set to102, andgpais set to3.5.The memory address of this second object is assigned to the
student2variable.
- Analysis
After execution, student1 and student2 are two distinct reference variables. They point to two different Student objects in memory. Although both objects were created from the same Student class (blueprint), they have their own independent state (their own name, studentID, and gpa values). Modifying one object will not affect the other.
Java Syntax Quick-Reference
new: The keyword used to allocate memory and create a new object instance.ClassName(arguments): The syntax for calling a constructor.ClassNamemust match the class name exactly, andargumentsmust match the type and order of the constructor's parameters.
Core Code Examples & Terminology
Class: A template or blueprint for creating objects. It defines the attributes and methods that characterize any object of that class.
Object: A specific instance of a class. It is a concrete entity that has its own state (values for its instance variables) and access to the behaviors (methods) defined by its class.
Instance: Another word for an object. To create an object is to "instantiate" a class.
Constructor: A special method that is automatically called when an object is created with the
newkeyword. Its primary job is to initialize the object's instance variables.newkeyword: The Java keyword that dynamically allocates memory for a new object and returns a reference to that memory.Core Snippet 1 (Declaring an object reference):
Student firstStudent;This line declares a variable
firstStudentthat can hold a reference to aStudentobject, but no object has been created yet (its value isnull).Core Snippet 2 (Instantiating an object):
Student firstStudent = new Student("Maria", 205, 4.0);This line declares a reference, creates a new
Studentobject in memory, and calls the constructor to initialize it.
Core Skill Check
Code Tracing: What is printed by the last line of this Java code?
// Assume the Student class from above exists Student s1 = new Student("Zoe", 300, 3.1); Student s2 = new Student("Leo", 301, 3.9); s1 = s2; s1.displayInfo();Answer:
Name: Leo, ID: 301Debugging: Identify the compile-time error in this Java code.
// Assume the Student class from above exists Student newStudent = Student("Carlos", 404, 2.5);Answer: The
newkeyword is missing. It should benew Student(...).Application: Write a single line of Java code that creates a
Studentobject referenced by a variable namedtopStudent, with the name "Eve", ID 500, and GPA 4.0.Answer:
Student topStudent = new Student("Eve", 500, 4.0);
Common Misconceptions & Errors
Forgetting the
newkeyword: WritingStudent s = Student("name", 1, 3.0);is a common syntax error. You must usenewto create an object.Confusing Declaration with Instantiation: The statement
Student myStudent;only declares a reference variable; it does not create an object. The variablemyStudentwill benulluntil it is assigned an object withnew.Mismatched Constructor Arguments: Calling
new Student("Alex", 3.9);will cause a compile-time error if the only available constructor requires three arguments (e.g., aString, anint, and adouble). The arguments in the call must match the parameters of a defined constructor in number, type, and order.Confusing the Class with an Object: You cannot call non-static methods on a class name (e.g.,
Student.displayInfo()). You must first create an object (e.g.,Student s = new Student(...)) and then call the method on that specific object (s.displayInfo()).
Summary
A class serves as a blueprint, defining the structure and behaviors for a type of entity. An object is a concrete instance created from that class, with its own unique state stored in instance variables. The new keyword is the fundamental mechanism in Java for instantiating an object, which allocates memory for it. When an object is created, a constructor is automatically called to perform initial setup, typically by assigning values to the instance variables. This separation of the blueprint (class) from the product (object) is a cornerstone of object-oriented programming, enabling the creation of complex and organized software.