No history yet

Objects and Methods

Classes and Objects

In programming, a class is a blueprint for creating things. Think of it like an architect's plan for a house. It defines all the properties (like number of rooms, color of the walls) and behaviors (like open a door, turn on a light) that a house can have.

An object is an actual house built from that blueprint. You can build many houses (objects) from a single blueprint (class), and each one is a distinct instance. One house might have blue walls, and another might have white walls, but they are both built from the same fundamental plan.

A class is the blueprint. An object is the real thing created from that blueprint.

Much of modern programming involves using pre-existing classes to create objects that solve parts of our problem. We don't always need to draw the blueprint from scratch; we can use well-designed plans that others have already created. Java provides a rich library of these classes for us to use.

Creating and Using Objects

To create an object from a class, we use a special method called a constructor. The new keyword in Java signals that we are calling a constructor to create a new instance of a class. Often, we pass arguments to the constructor to set up the initial state of our new object.

// Using a constructor to create a String object
String greeting = new String("Hello");

// We can ask the object to perform actions using methods
// A method is a behavior defined in the class blueprint
int length = greeting.length(); // length() is a method

System.out.println(length); // Prints 5

In the example above, new String("Hello") creates a new String object with the initial value "Hello". We store a reference to this object in the greeting variable.

Once we have an object, we use dot notation (.) to call its methods. A method is a function that belongs to an object, allowing it to perform an action or compute a value. Some methods, like length(), don't need any extra information. Others require you to pass in arguments.

The String Class

The String class is one of the most commonly used in Java. It's important to know that String objects are immutable. This means that once a String object is created, its value cannot be changed. Any method that seems to modify a string, like converting it to uppercase, actually returns a brand new String object with the change.

String text = "Computer Science";

// substring() returns a new string
// It includes the character at the start index but not the end index
String sub = text.substring(0, 8); // sub is "Computer"

// indexOf() finds the starting position of a substring
int position = text.indexOf("Science"); // position is 9

// equals() checks if two strings have the exact same sequence of characters
boolean isEqual = sub.equals("Computer"); // isEqual is true

Wrapper and Math Classes

Java has primitive types like int and double which are not objects. Sometimes, we need to treat these values as if they were objects. For this, Java provides wrapper classes for each primitive type.

Primitive TypeWrapper Class
intInteger
doubleDouble
booleanBoolean
charCharacter

You can create an Integer object from an int, which allows you to use it in contexts that require objects. The conversion between primitives and their wrapper types is often handled automatically by Java in a process called autoboxing and unboxing.

Integer students = 25; // Autoboxing: int to Integer
int classSize = students; // Unboxing: Integer to int

Another incredibly useful class is Math. This class is a collection of static methods for performing mathematical operations. Static means the methods belong to the class itself, not to an instance of the class. Because of this, you don't use the new keyword to create a Math object. You just call the methods directly on the class.

// Get the absolute value
double absValue = Math.abs(-10.5); // 10.5

// Raise to a power (base, exponent)
double power = Math.pow(2, 3); // 8.0 (2^3)

// Calculate the square root
double root = Math.sqrt(81); // 9.0

// Generate a random double between 0.0 (inclusive) and 1.0 (exclusive)
double randomNum = Math.random(); // e.g., 0.734...

Understanding Null

When you declare an object reference variable, you can set it to a special value: null. A null reference means the variable doesn't point to any object in memory. It's like having a label for a box, but the box doesn't exist yet.

String name = null;

If you try to call a method on a null reference, your program will crash. This is because you're trying to ask a non-existent object to perform an action. This common runtime error is called a NullPointerException.

String name = null;
int len = name.length(); // Throws NullPointerException!

It's a good practice to check if an object is null before you try to use it, especially if its value comes from an external source or another part of the program that might not have assigned it yet.

Quiz Questions 1/6

In the house blueprint analogy, what does an 'object' represent?

Quiz Questions 2/6

Which Java keyword is essential for creating a new instance (an object) from a class?