Classes and Objects

Naveen AnamaneniUpdated · 5 min read

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:

Ticket.java
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

One class, many objects, each with its own state
Booking.java▶ Try it
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();
    }
}
Output
Navika, berth 23, Rs. 450
Advitha, berth 61, Rs. 1180

How it works

  1. Line 14: new Ticket() creates a new object on the heap and returns a reference to it, stored in t1.
  2. Lines 15 to 17 set t1's own fields with the dot operator: t1.passenger.
  3. Lines 19 to 22 create a second, completely separate object.
  4. 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:

OwnState.java▶ Try it
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);
    }
}
Output
Gate A: 3, Gate B: 1

Both 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

RuleExample
A public class must be in a file with the same namepublic class Ticket → Ticket.java
One file can contain only one public top-level classHelpers in the same file must not be public
Class names use PascalCaseBankAccount, not bank_account
A class can hold fields, methods, constructors, blocks and nested classesAll 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

  1. Easy: Write a Book class with title, author and price, create two books, and print them.
  2. Harder: Add a method applyDiscount(int percent) to Book that lowers the price. Show that discounting one book doesn't change the other.

Quick check: Classes and objects

4 questions
1What does new Ticket() create?
2How do you set the berth field of the object t1?
3Two Counter objects each call tap(). How many count values exist?
4Where must public class Ticket be saved?

Key Takeaways

Was this tutorial helpful?

Lesson 93 of 482