Java Programming, OOP in Java · December 2, 2026

Java for Beginners, Lesson 29: Introduction to OOP: Classes and Objects in Java

Java for Beginners · Module 6: Objects and Revision


🎯 Thinking in Objects

Look around: a student, a book, a bank account. Each has data (name, price, balance) and actions (display, withdraw). Java organises programs around such things, called objects. A class is the blueprint that describes them, and an object is one real thing built from the blueprint.

📌 A class defines fields (data) and methods (actions). An object is an instance of a class, created with new. This style of programming is called Object-Oriented Programming (OOP).
Class
the blueprint: Student
new ➜
Object s1
name = Ajay
roll = 101
Object s2
name = Rahul
roll = 102
One class can create any number of objects. Each object has its own copy of the fields.

Figure 1: A class is a blueprint, objects are the things built from it.

1️⃣ Your First Class

Save this as Student.java. Then, in a second file, create objects from it. Remember from Lesson 5 that a public class must live in a file with the same name.

File 1: Student.java

public class Student { String name; int roll; double cgpa; void display() { System.out.println(roll + ” | ” + name + ” | CGPA ” + cgpa); } boolean isTopper() { return cgpa >= 9.0; } }

File 2: Main1.java

public class Main1 {
    public static void main(String[] args) {
        Student s1 = new Student();
        s1.name = "Ajay";
        s1.roll = 101;
        s1.cgpa = 9.2;

        Student s2 = new Student();
        s2.name = "Rahul";
        s2.roll = 102;
        s2.cgpa = 7.8;

        s1.display();
        s2.display();
        System.out.println(s1.name + " topper? " + s1.isTopper());
        System.out.println(s2.name + " topper? " + s2.isTopper());

        Student s3 = new Student();
        s3.display();

        Student alias = s1;
        alias.cgpa = 9.9;
        System.out.println("s1.cgpa after alias change = " + s1.cgpa);
        System.out.println("s1 == alias ? " + (s1 == alias));
    }
}
🖥️ Compile both files, then run Main1:
101 | Ajay | CGPA 9.2
102 | Rahul | CGPA 7.8
Ajay topper? true
Rahul topper? false
0 | null | CGPA 0.0
s1.cgpa after alias change = 9.9
s1 == alias ? true
PartWhat it isExample
Fields (attributes)variables that hold the object’s dataString name; int roll;
Methods (behaviour)actions the object can performvoid display()
Constructorspecial method that runs on new; same name as the class, no return typeBook(String title, double price)
thisrefers to the current objectthis.title = title;
static memberbelongs to the class, shared by all objectsstatic int count

Figure 2: The building blocks of a class.

  • new Student() creates an object in memory and gives back a reference to it. s1 and s2 are two separate objects with their own data.
  • The dot reaches into an object: s1.name is the field, s1.display() is the method.
  • Methods of the class run on that object: s1.isTopper() uses s1’s CGPA.
  • s3 was never filled in, so it holds the defaults: 0 for numbers and null for the String (Lesson 11).
  • This also explains static from Lesson 25: main and its helpers are static because they belong to the class, not to any object. A normal (non-static) method needs an object.
s1 ➜ Student object (Ajay, 9.2) ⬅ alias
alias = s1 copies the reference, not the object. Both names reach the same object, just as with arrays (Lesson 21).

Figure 3: Two variables can point to one object.

2️⃣ Constructors, this and static

A constructor sets up an object at the moment it is created, so you do not have to assign every field by hand.

File 3: Book.java

public class Book { String title; double price; static int count = 0; Book(String title, double price) { this.title = title; this.price = price; count++; } Book(String title) { this(title, 199.0); } void show() { System.out.println(title + ” costs Rs ” + price); } static void printCount() { System.out.println(“Books created: ” + count); } }

File 4: Main2.java

public class Main2 {
    public static void main(String[] args) {
        Book b1 = new Book("Java Basics", 450.0);
        Book b2 = new Book("DSA Notes");
        b1.show();
        b2.show();
        Book.printCount();
        System.out.println("count seen via b1: " + b1.count);
    }
}
🖥️ Output:
Java Basics costs Rs 450.0
DSA Notes costs Rs 199.0
Books created: 2
count seen via b1: 2
  • The constructor has the same name as the class and no return type. It runs automatically when new is used.
  • this.title = title;: this.title is the object’s field and plain title is the parameter. this means “the object being built” and settles the name clash (compare shadowing in Lesson 11).
  • Constructors can be overloaded (Lesson 25). this(title, 199.0) reuses the first constructor to give a default price.
  • static int count belongs to the class, not to each object. All books share it, so it counts how many were created. Call static members through the class name, Book.printCount().
  • Reading a static field through an object (b1.count) works but is poor style, and the compiler warns about it.
  • If you write no constructor, Java gives your class an empty default one. As soon as you write any constructor, that default disappears.

3️⃣ Encapsulation: Protecting the Data

ModifierVisible from
privateinside the same class only
(none)the same package
protectedsame package and subclasses
publiceverywhere
Good practice: make fields private, and give controlled access through public methods (encapsulation).

Figure 4: Access modifiers.

If fields are open to everyone, any code can put nonsense in them, such as a negative bank balance. Encapsulation means making fields private and allowing changes only through methods that check the rules.

File 5: Account.java

public class Account { private double balance; Account(double opening) { balance = opening; } void deposit(double amount) { if (amount > 0) { balance += amount; } } boolean withdraw(double amount) { if (amount > 0 && amount <= balance) { balance -= amount; return true; } return false; } double getBalance() { return balance; } }

File 6: Main3.java

public class Main3 {
    public static void main(String[] args) {
        Account acc = new Account(1000);
        acc.deposit(500);
        System.out.println("balance = " + acc.getBalance());
        System.out.println("withdraw 2000 ok? " + acc.withdraw(2000));
        System.out.println("withdraw 300 ok?  " + acc.withdraw(300));
        System.out.println("balance = " + acc.getBalance());
        System.out.println(acc);
    }
}
🖥️ Output (the last line has a different number each run):
balance = 1500.0
withdraw 2000 ok? false
withdraw 300 ok? true
balance = 1200.0
Account@5e2de80c
  • The balance can only change through deposit and withdraw, which refuse bad amounts. Outside code can read it through the getter getBalance().
  • Printing an object with no toString() method gives the class name and an address-like code, as it did for arrays (Lesson 21). Writing your own toString() is a good first thing to learn next.

4️⃣ Errors Beginners Meet

Touching a private field

public class Bad1 {
    public static void main(String[] args) {
        Account acc = new Account(500);
        acc.balance = 1000000;
    }
}
🖥️ Compiler message:
Bad1.java:4: error: balance has private access in Account
acc.balance = 1000000;
^
1 error
  • This is encapsulation doing its job. Use deposit() instead.

No matching constructor

public class Bad2 {
    public static void main(String[] args) {
        Book b = new Book();
    }
}
🖥️ Compiler message:
Bad2.java:3: error: no suitable constructor found for Book(no arguments)
Book b = new Book();
^
constructor Book.Book(String,double) is not applicable
(actual and formal argument lists differ in length)
constructor Book.Book(String) is not applicable
(actual and formal argument lists differ in length)
1 error
  • Once you write your own constructors, Java no longer supplies the empty one. Pass the arguments they need, or add a no-argument constructor.

Using an object that was never created (runtime)

public class Npe3 {
    public static void main(String[] args) {
        Student s = null;
        s.display();
    }
}
🖥️ Runtime error:
Exception in thread “main” java.lang.NullPointerException: Cannot invoke “Student.display()” because “<local1>” is null
at Npe3.main(Npe3.java:4)
  • Declaring Student s; creates only a variable. The object comes from new (Lesson 23 showed the same NullPointerException with Strings).

⚠️ Common Mistakes

MistakeProblemFix
Declaring Student s; and using itNo object yet (null)Student s = new Student();
Giving a constructor a return typeIt becomes an ordinary methodNo return type, same name as the class
Parameter with the same name as a field and no thisAssigns the parameter to itselfthis.name = name;
Making every field publicAny code can break the dataUse private plus getters and setters
Calling an instance method from main without an objectnon-static method errorCreate an object first
Expecting alias = s1 to copy the objectCopies only the referenceCreate a new object and copy the fields

❓ Frequently Asked Questions

Q1. What is the difference between a class and an object?
A class is the plan. An object is a real thing built from the plan. One class, many objects.

Q2. Can a file hold more than one class?
Yes, but only one can be public, and the file takes that name. Beginners keep one class per file.

Q3. When is a constructor called?
Exactly once per object, at the moment of new.

Q4. What comes next in OOP?
Inheritance, polymorphism, abstract classes and interfaces. These are the topics of the next series.

✅ Key Takeaways

  • A class is a blueprint with fields and methods. An object is created from it with new.
  • The dot (obj.field, obj.method()) reaches inside an object.
  • A constructor initialises a new object. this refers to the current object.
  • static members belong to the class and are shared by all objects.
  • Encapsulation: private fields with public methods that enforce the rules.
  • Object variables hold references, so two names can share one object.
🎓 Practice questions: (1) Create a Rectangle class with width and height, a constructor and methods area() and perimeter(). (2) Add a static counter to count how many Rectangle objects have been created. (3) Make the fields of Student private and add getters and setters. The setter for CGPA should reject values above 10. (4) Why does this.name = name; need this? (5) Explain what happens in memory when you write Student alias = s1;.
All 30 lessons in this series (open course page)

Module 1 · Getting Started

Module 2 · Building Blocks

Module 3 · Operators

Module 4 · Control Flow

Module 5 · Data and Methods

Module 6 · Objects and Revision