Classes and Objects
A builder uses one architect's plan to build ten identical flats. Each flat has its own owner, its own furniture and its own electricity bill, but they all follow the same plan. In Java, the plan is a class and each flat is an object. This lesson shows how to write a class, create objects from it, and see that each object really does keep its own data.
Writing a Class
A class lists the fields (data) and methods (behavior) that every object of that kind will have:
public class Ticket {
String passenger; // field
int berth; // field
int fare; // field
void print() { // method
System.out.println(passenger + ", berth " + berth + ", Rs. " + fare);
}
}This creates no ticket yet. It only describes what a ticket is.
Creating Objects
public class Booking {
static class Ticket {
String passenger;
int berth;
int fare;
void print() {
String line = passenger + ", berth " + berth;
System.out.println(line + ", Rs. " + fare);
}
}
public static void main(String[] args) {
Ticket t1 = new Ticket();
t1.passenger = "Navika";
t1.berth = 23;
t1.fare = 450;
Ticket t2 = new Ticket();
t2.passenger = "Advitha";
t2.berth = 61;
t2.fare = 1180;
t1.print();
t2.print();
}
}Navika, berth 23, Rs. 450
Advitha, berth 61, Rs. 1180How it works
- Line 14:
new Ticket()creates a new object on the heap and returns a reference to it, stored int1. - Lines 15 to 17 set t1's own fields with the dot operator:
t1.passenger. - Lines 19 to 22 create a second, completely separate object.
- Lines 24 and 25 call
print()on each object. The same method prints different data, because each call uses the fields of the object it's called on.
Ticket here is written inside Booking (as a static class) only so that the example fits in one runnable file. In real projects, each public class goes in its own file: Ticket.java, Booking.java.
Try it yourself: create a third ticket for Srihitha in berth 24, and print it.
Each Object Has Its Own State
Changing one object never changes another:
public class OwnState {
static class Counter {
int count;
void tap() { count++; }
}
public static void main(String[] args) {
Counter gateA = new Counter();
Counter gateB = new Counter();
gateA.tap(); gateA.tap(); gateA.tap();
gateB.tap();
System.out.println("Gate A: " + gateA.count
+ ", Gate B: " + gateB.count);
}
}Gate A: 3, Gate B: 1Both counters started at 0 (the default for int fields, see "Default Values of Data Types"). gateA was tapped three times, gateB once; each kept its own count.
Rules for Class Files
| Rule | Example |
|---|---|
A public class must be in a file with the same name | public class Ticket → Ticket.java |
One file can contain only one public top-level class | Helpers in the same file must not be public |
| Class names use PascalCase | BankAccount, not bank_account |
| A class can hold fields, methods, constructors, blocks and nested classes | All covered in this chapter and in "Inner Classes in Java" |
Common Mistakes
Using a class name where an object is needed. Ticket.print() doesn't compile for an instance method; you need an object: t1.print().
Forgetting new. Ticket t1; declares a variable but creates no object; using t1 before assigning it doesn't compile.
Thinking two objects share fields. Instance fields are per object; only static fields are shared (see "Java Static Keyword").
Interview Corner
What is a class and what is an object?
A class is a blueprint that defines the fields and methods its objects will have. An object is an instance of a class, created with new, with its own copy of the instance fields. One class can have many objects.
What does the new keyword do?
It allocates memory for a new object on the heap, sets its fields to default values, runs a constructor, and returns a reference to the object.
Practice
- Easy: Write a
Bookclass withtitle,authorandprice, create two books, and print them. - Harder: Add a method
applyDiscount(int percent)toBookthat lowers the price. Show that discounting one book doesn't change the other.
Key Takeaways
Was this tutorial helpful?