Skip to content

Beginner · Classes and objects · topic 16 of 60 · 25 min

Classes and objects

Explanation

A class is a blueprint that describes data (fields) and behaviour (methods). An object is one thing built from that blueprint with new, holding its own field values. Variables hold references to objects; a reference can be null. Calling methods on objects with the dot operator is the heart of object-oriented programming.

Why classes?

So far you have used separate variables and static methods. Real programs model things: an account has an owner and a balance and can deposit and withdraw; a product has a name, a price and stock. A class groups the data of a thing with the code that works on that data. This style is object-oriented programming (OOP).

java
public class BankAccount {
    String owner;          // fields: the data each object has
    double balance;

    void deposit(double amount) {   // instance method: works on THIS object's fields
        balance += amount;
    }

    void show() {
        System.out.println(owner + " has Rs " + balance);
    }
}

Creating objects

java
BankAccount a = new BankAccount();   // new builds an object on the heap
a.owner = "Asha";
a.deposit(5000);

BankAccount b = new BankAccount();   // a second, independent object
b.owner = "Ravi";
b.deposit(1200);

a.show();   // Asha has Rs 5000.0
b.show();   // Ravi has Rs 1200.0

Each object has its own copy of the fields. a.deposit changes only a's balance. Fields get default values (0, 0.0, false, null) if you do not set them.

References and the heap

Objects live in a memory area called the heap. A variable like a does not contain the object; it holds a reference (like an address) to it. Assigning BankAccount c = a; copies the reference, so c and a refer to the same account. A reference that points to nothing is null; calling a method on null throws NullPointerException.

java
BankAccount c = a;     // same object as a
c.deposit(100);
a.show();              // Asha has Rs 5100.0

BankAccount nobody = null;
// nobody.show();      // NullPointerException

Instance members versus static members

Fields and methods without static belong to each object (instance members): every account has its own balance. Members marked static belong to the class as a whole (topic 4). Inside an instance method you can use fields directly; the full form is this.balance, where this means "the object this method was called on".

Careful: Making every field public and changing it from anywhere (a.balance = -999999;) defeats the purpose of objects: any code can put the object into an invalid state. Topic 3 shows how to keep fields private and change them only through methods that check the rules.
Think of it like this: A class is like the architect's drawing of a flat type in a housing society ("2BHK, Type A"). Each object is an actual flat built from that drawing: same layout, but each has its own owner, its own furniture and its own electricity reading.
Tip: One public class per file, named like the file. Name classes with nouns (Invoice, Train, Patient) and methods with verbs (calculateTotal, book, discharge).

Need help?

Stuck on a word or an idea? Search this course, or every course, and jump straight to the explanation or a worked question.

Try:

Watch the lesson

Classes and objects · 1/6

Classes and objects

In this lesson you will create your own classes and objects.

Prefer a video by a teacher? Find free videos on “java classes and objects tutorial for beginners oop” on YouTube ↗

In real life: Products in an online store

An e-commerce catalogue has thousands of products. Each is an object of one Product class, with its own name, price and stock, and a method to check availability. The code that lists products just calls methods on each object.

java
class Product {
    String name;
    double price;
    int stock;

    boolean isAvailable(int qty) { return stock >= qty; }
}
// Product p = new Product(); p.name = "Steel bottle"; p.price = 349; p.stock = 12;
// p.isAvailable(2) → true

Practice (0/3 done)

Task 1 · Question

What does this print? class Counter { int n; void inc() { n++; } } … Counter a = new Counter(); Counter b = a; Counter c = new Counter(); a.inc(); b.inc(); c.inc(); System.out.println(a.n + " " + c.n);

Task 2 · Code · Javascript

The same class idea in JavaScript, which runs here: write a class BankAccount with a constructor(owner) that sets balance to 0, deposit(amount) and withdraw(amount) (returns false and changes nothing if amount > balance), and a show() that returns "<owner>: Rs <balance>".

Task 3 · Practice

Write a Java class Student with fields name, roll and marks (int[]), and methods total() and average(). In main, create three Student objects and print each one's average.

Quick quiz

Question 1

1.What does the new keyword do?

Question 2

2.Two objects of the same class…

Question 3

3.What is the default value of an uninitialised String field?

Question 4

4.Inside an instance method, what does this refer to?

Read more (free)

Open a question to see the answer and why. The first ones are this topic's own quiz, so try the quiz above before you peek.

What does the new keyword do?

Answer: Creates an object and returns a reference to it

new allocates and initialises a new object.

Two objects of the same class…

Answer: Each have their own copies of instance fields

Instance fields belong to each object.

What is the default value of an uninitialised String field?

Answer: null

Object fields default to null (unlike local variables, which have no default).

Inside an instance method, what does this refer to?

Answer: The object the method was called on

this is the current object.

A static member variable is…Related

Answer: shared by the whole class, one copy in total

Static members belong to the class, not to individual objects.

From Classes and objects: data plus behaviour

Without overriding ToString, what does printing an object of class City show?Related

Answer: Its class name (like City)

The default ToString returns the type's full name.

From Classes, objects and constructors

What is the difference between a class and an object?Related

Answer: A class is the blueprint; an object is one thing made from it

One class can make many objects, each with its own data.

From Classes and objects

What makes a class field private?Related

Answer: A leading #

#name fields are truly private; _name is only a naming convention.

From Classes

Pass the quiz (60% or more) or mark this topic as done when you are ready.

Your progress is saved on this device only.

Next steps

  1. 4 more topics in “Classes and objects” before its exam: Constructors and this, Encapsulation: private fields, getters and setters, static members and final, toString, equals, hashCode and records.
  2. Module 4 exam: Classes and objects · 12 questions · 25 min, without help. 5 topics of this module still to finish first.
  3. Then the next module, Inheritance, polymorphism and interfaces. 60 topics left in the course before the final exam.

← Previous: Wrapper classes and autoboxing