Sub topic 11
Classes and Objects
In this chapter, we move from writing loose statements into the heart of Java: classes and objects. A class is a blueprint; an object is a thing built from that blueprint. Almost everything you will ever write in Java involves defining classes and creating objects from them.
Prerequisites for this chapter: you should be comfortable with variables and types, methods, parameters, and return values, and you should know what an array is and how a for loop works. You do not need any prior object-oriented programming experience — we will build that up from zero.
What Is a Class, and What Is an Object?
A class is a description of a kind of thing. It says what data the thing holds (its fields) and what actions it can perform (its methods).
An object (also called an instance) is a concrete example created from a class. If Dog is the class — the idea of a dog with a name that can bark — then your dog Rex is an object: one actual instance with an actual name.
A helpful comparison: a class is like a cookie cutter, and objects are the cookies. The cutter defines the shape. You can press out as many cookies as you want, and each cookie is separate — changing one cookie does not change the others.
Before classes, all our programs were just loose statements in main. That works for tiny scripts, but as programs grow, you need a way to group related data and behavior together. That is exactly what a class does.
Why Classes Matter
- They keep related data together. A dog's name, age, and weight travel as one unit.
- They bundle behavior with data. The
speakmethod lives next to the name it uses. - They let you make many similar things without copying code.
- They make large programs understandable: you think in terms of "things" rather than a flood of variables.
Defining a Class
Here is the smallest useful class definition:
class Dog {
String name;
}This class has one field named name, of type String. A field is a variable that belongs to each object of the class. Every Dog object will have its own name.
You cannot do much with a bare field yet, though. Fields inside a class work best alongside methods. Let's add one:
class Dog {
String name;
void speak() {
System.out.println(name + " says Woof!");
}
}Notice something new: speak() refers to name without any extra work. Because speak belongs to the class, it automatically works with the name field of whatever object calls it. That is the core idea of objects: data and the methods that use it travel together.
Creating and Using Objects
A class definition is just a plan. To get a real object, you use the new keyword:
Dog d = new Dog();
d.name = "Rex";
d.speak();Let's read this carefully:
new Dog()creates a newDogobject in memory.Dog d = ...stores a reference to that object in the variabled. A reference is like an address: it tells Java where the object lives, not the object itself.d.name = "Rex";uses dot notation to reach inside the object and set its field.d.speak();calls the object's method. When it runs,namemeans "the name of the objectdpoints to."
You can make many objects from one class, each independent:
Dog d1 = new Dog();
d1.name = "Rex";
Dog d2 = new Dog();
d2.name = "Bella";
d1.speak(); // Rex says Woof!
d2.speak(); // Bella says Woof!Each object has its own copy of the fields. Setting d2.name does not touch d1.name.
References and Independence
Because a variable holds a reference, not the object itself, assignment copies the reference:
Dog a = new Dog();
a.name = "Rex";
Dog b = a; // b now points to the SAME object as a
b.name = "Bella";
System.out.println(a.name); // Bella!Only one object was created. Both a and b point to it, so changing it through b is visible through a. If you truly want two separate dogs, you must call new twice.
Fields and Methods Together
A realistic class usually has several fields and several methods. Here is a BankAccount:
class BankAccount {
String owner;
double balance;
void deposit(double amount) {
balance = balance + amount;
}
void withdraw(double amount) {
if (amount <= balance) {
balance = balance - amount;
} else {
System.out.println("Not enough funds for " + owner);
}
}
void printSummary() {
System.out.println(owner + " has $" + balance);
}
}And a program that uses it:
public class Main {
public static void main(String[] args) {
BankAccount acct = new BankAccount();
acct.owner = "Maya";
acct.balance = 100.0;
acct.deposit(50.0);
acct.withdraw(30.0);
acct.printSummary(); // Maya has $120.0
}
}Note what happened inside deposit: it read and changed balance directly. The method and the field live inside the same object, so they can work on the data directly. Code outside the class (like main) must go through dot notation. This separation — methods guarding access to data — is why objects help you write correct programs: all the rules about a bank account live in one place.
Objects and Arrays
Since objects are values, you can store them in arrays just like numbers:
Dog[] kennel = new Dog[3];
kennel[0] = new Dog();
kennel[0].name = "Rex";
kennel[1] = new Dog();
kennel[1].name = "Bella";
kennel[2] = new Dog();
kennel[2].name = "Sid";
for (Dog d : kennel) {
d.speak();
}One subtlety: new Dog[3] creates the array, but it does not create any dogs. An array of objects starts out filled with null, a special value meaning "points to nothing." Calling a method on a null reference causes an error, so you must fill each slot with a real object first.
How It All Fits: A Complete Program
Let's assemble everything into one complete, runnable program with two classes: a data class and the entry-point class.
class Point {
int x;
int y;
void moveRight(int amount) {
x = x + amount;
}
int distanceFromOrigin() {
return (int) Math.sqrt(x * x + y * y);
}
void print() {
System.out.println("(" + x + ", " + y + ")");
}
}
public class Main {
public static void main(String[] args) {
Point p = new Point();
p.x = 3;
p.y = 4;
p.moveRight(2);
p.print(); // (5, 4)
System.out.println(p.distanceFromOrigin()); // 5
}
}Run this and you will see (5, 4) and 5 printed. The Point class bundles data (x, y) with behavior (moveRight, distanceFromOrigin, print), and Main creates and drives an object.
Here is the overall picture of how the pieces relate:
Common Mistakes and How to Avoid Them
Beginners run into the same handful of problems with objects. Here they are, with fixes:
- Using the class name as if it were an object. Writing
Dog.speak();fails.speakbelongs to objects, not the class. You mustnewan object first. - Forgetting
new. DeclaringDog d;creates only a variable, which holdsnull. You still needd = new Dog();. - Expecting assignment to copy objects.
Dog b = a;copies the reference, not the dog. Two names, one object. - Calling methods on
null. Always create the object before calling its methods, and check array slots are filled before looping over them. - Mixing up class and object state. A field describes each object, not all of them. If every dog should have its own name,
nameas a field is correct.
Looking Ahead
You now know how to define a class with fields and methods, create objects with new, connect data and behavior, and store objects in arrays. In the next chapters, we will make object creation cleaner with constructors (special methods that run automatically when you write new), and we will see how a class can inherit the fields and methods of another class, so similar classes can share code.
Exercise
What is the difference between a class and an object?
Show answer
A class is the blueprint — it defines what fields and methods objects of that kind will have. An object is one concrete instance created from that blueprint with new, with its own copy of the fields. One class can produce any number of independent objects.
Exercise
In the code below, what does the final print statement output? Dog a = new Dog(); a.name = "Rex"; Dog b = a; b.name = "Bella"; System.out.println(a.name);
Show answer
It prints Bella. The line Dog b = a; copies the reference, so a and b point to the same single object. Changing b.name changes that object's name, which a also sees.
Exercise
You write: Dog[] dogs = new Dog[2]; then immediately call dogs[0].speak(); What happens and why?
Show answer
The program fails with a NullPointerException. new Dog[2] creates the array but fills it with null — no Dog objects exist yet. You must assign real objects (for example dogs[0] = new Dog();) before calling methods on the slots.