Welcome to the World of Objects!
In the previous unit, we looked at primitive types (like int and double), which are like simple ingredients. In this unit, Using Objects and Methods, we start building the "recipes." We will learn how to use pre-written code to create Objects and make them do work using Methods. This is the heart of Object-Oriented Programming (OOP), which is how modern software is built!
Don't worry if this seems a bit abstract at first. Think of it like learning to drive a car: you don't need to know how the engine works to use the steering wheel and the pedals!
1. Objects: Blueprints vs. The Real Deal
To understand objects, we must understand the difference between a Class and an Object.
The Analogy
Imagine an architect's blueprint for a house. The blueprint isn't a house you can live in; itβs just the plan. Using that one blueprint, you can build five different houses. The blueprint is the Class, and each specific house is an Object.
Key Terms:
- Class: A template or blueprint for creating objects. It defines what the object will know and what it will do.
- Object: A specific "instance" of a class. It has its own data and can perform actions.
- Reference: A variable that holds the "address" of where an object is stored in the computer's memory.
Did you know? Even though two houses (objects) are built from the same blueprint (class), one might be painted blue and the other red. They are independent of each other!
Quick Review: An Object is the actual thing we use in our code, while the Class is the rulebook that defines it.
2. Creating Objects with Constructors
To bring an object to life, we use a special piece of code called a Constructor. In Java, we use the keyword new to trigger the constructor.
The Syntax
ClassName variableName = new ClassName(parameters);
For example, if we have a class called Turtle:
Turtle myTurtle = new Turtle();
Whatβs happening here?
1. Turtle myTurtle: We create a variable named myTurtle that is allowed to hold a Turtle object.
2. new: This keyword tells Java to set aside space in memory for a new object.
3. Turtle(): This calls the constructor to initialize (set up) the object.
The Null Keyword:
If you declare a variable but don't use new, like this: Turtle yurtle;, the variable is null. This means it doesn't point to any object yet. If you try to make a null variable do something, Java will throw a NullPointerException. Think of it like trying to call a phone number that hasn't been assigned to a phone yet!
Key Takeaway: Use new to create an instance of a class. Without it, your object variable is empty (null).
3. Methods: Making Objects Do Work
A Method is a block of code that performs a specific task. We call (or "invoke") a method using the dot operator (.).
Calling Methods
If we have our myTurtle object, we can make it move:
myTurtle.forward(100);
Anatomy of a Method Call:
- Object Name: myTurtle
- Dot Operator: . (This says "go inside the object and find...")
- Method Name: forward
- Parameters/Arguments: (100) (The specific information the method needs to work).
Types of Methods
1. Non-void Methods: These do a calculation and return a value to you. Think of it like asking a friend, "What time is it?" They give you back an answer.
2. Void Methods: These perform an action but don't return a value. Think of it like telling a friend, "Sit down." They do it, but they don't give you an answer back.
Common Mistake: Forgetting the parentheses! Even if a method doesn't need info (parameters), you still need empty parentheses: myTurtle.dance();
Key Takeaway: Methods are the "verbs" of programming. Use the dot operator to tell an object what to do.
4. The String Class
The String class is one of the most important classes in Java. A String is a sequence of characters inside double quotes.
String Indices
This is the most important rule: Java starts counting at 0!
In the String "Java":
- Index 0 is 'J'
- Index 1 is 'a'
- Index 2 is 'v'
- Index 3 is 'a'
Essential String Methods
- int length(): Returns the number of characters. "Hi".length() is 2.
- String substring(int from, int to): Returns a slice of the string. Warning: It includes the from index but stops right before the to index.
Example: "Computer".substring(0, 3) returns "Com".
- int indexOf(String str): Finds where a word starts. Returns -1 if it's not found.
- boolean equals(String other): Use this to compare if two strings are identical. Never use \( == \) to compare Strings!
Memory Aid: For substring(start, end), the length of the result is always \( end - start \).
Quick Review: Strings are objects. Start counting at 0. Use .equals() for comparison.
5. Wrapper Classes: Integer and Double
Sometimes Java needs a primitive (like int) to act like an object. We use Wrapper Classes for this.
- Integer wraps an int.
- Double wraps a double.
Autoboxing and Unboxing
- Autoboxing: Java automatically turning an int into an Integer object.
- Unboxing: Java automatically turning an Integer object back into a simple int.
Key Terms:
- Integer.MIN_VALUE: The smallest possible int value \( (-2^{31}) \).
- Integer.MAX_VALUE: The largest possible int value \( (2^{31} - 1) \).
Key Takeaway: Wrapper classes allow primitive values to be treated as objects when necessary.
6. The Math Class
The Math class is a "Static" class. This means you don't use new to create a Math object; you just call the methods directly using the class name.
Must-Know Math Methods
- Math.abs(value): Returns the absolute value (makes it positive).
- Math.pow(base, power): Returns \( base^{power} \). Always returns a double.
- Math.sqrt(value): Returns the square root as a double.
- Math.random(): Returns a random decimal between 0.0 (inclusive) and 1.0 (exclusive).
The Random Formula
To get a random integer in a specific range, use this pattern:
(int)(Math.random() * range) + min
Where range is (max - min + 1).
Example: To get a number between 5 and 10:
\( (int)(Math.random() * 6) + 5 \)
Quick Review: The Math class provides tools for complex math. Remember that Math.pow and Math.sqrt always give you a double!
Summary Checklist
- Can you explain the difference between a Class (blueprint) and an Object (house)?
- Do you remember to use the keyword new to create objects?
- Do you know that String indices start at 0?
- Can you calculate a substring correctly?
- Do you know that Math.random() never actually reaches 1.0?
You've got this! Using objects is the first major step toward writing powerful programs. Keep practicing those method calls!