Java Classes and Objects

Java Classes and Objects

7 min read

1. The problem with loose variables

With parallel arrays, a student's data is scattered: names[3], marks[3], rollNos[3]. Sort one array and forget the others, and the data is silently scrambled. Nothing in the code says "these three things belong together".

Object-oriented programming (OOP) solves this by bundling data (what something has) and behaviour (what it does) into one unit called an object.

2. Classes and objects

  • A class is a blueprint: it describes what data and behaviour a kind of thing has.

  • An object is a real thing built from that blueprint. One class can produce many objects.

Real-life analogy: House plans

An architect's plan for a 2BHK flat is the class. It describes rooms, doors and windows, but you can't live in a plan. The actual flats built from that plan are objects. Flat 101 and flat 202 have the same design but different families, furniture and paint. Each object has its own data.

3. A new project structure

Until now, each program was a single class containing main (and some static methods). From this session on, a program is made of several classes, each in its own file:

  1. In IntelliJ, create a new Java project. Inside the src folder, create two files: Student.java and Main.java.

  2. Each class goes in its own file, and the file name must match the class name.

  3. Class names use PascalCase: every word capitalised (Student, BankAccount).

Main.java holds our starting point:

Java
public class Main {    public static void main(String[] args) {        System.out.println("Hello from Main!");    }}

This is the same frame we've used since Session 1. What's new is that Student.java will hold a class without a main: a class that isn't a program on its own, but a design that Main uses.

Note: Back to the frame

The word class in public class Hello from Session 1 now has its meaning: every Java program is built from classes, and this session is about what a class really is. One more word of the frame is decoded; public and static remain

4. Defining a class

Java
// Student.javaclass Student {    // Fields: the data each Student object has    String name;    int rollNo;    double marks;    // Methods: what a Student can do    void printDetails() {        System.out.println(rollNo + ": " + name + " (" + marks + ")");    }    boolean hasPassed() {        return marks >= 40;    }}

Fields (also called instance variables) are variables declared in the class but outside any method. Every object gets its own copy.

5. Creating and using objects

Java
// Main.javapublic class Main {    public static void main(String[] args) {        Student s1 = new Student();   // create an object        s1.name = "Riya";        s1.rollNo = 12;        s1.marks = 88.5;        Student s2 = new Student();   // a second, separate object        s2.name = "Kabir";        s2.rollNo = 7;        s2.marks = 35;        s1.printDetails();                  // 12: Riya (88.5)        s2.printDetails();                  // 7: Kabir (35.0)        System.out.println(s2.hasPassed()); // false    }}
  • new Student() creates an object on the heap and gives back a reference to it.

  • The dot operator . means "go into this object": s1.name is s1's name, s1.printDetails() asks s1 to run its method.

  • Inside printDetails, name refers to the name of whichever object the method was called on. The same method prints Riya for s1 and Kabir for s2.

Two separate Student objects on the heap, each with its own fields.

This is exactly the same stack-and-heap picture as arrays in previous sessions. Arrays are objects too.

Fields get default values (0, 0.0, false, null) if you don't set them, unlike local variables inside methods, which must be set before use.

6. References, sharing and null

Java
Student a = new Student();a.name = "Riya";Student b = a;           // copies the reference: both point to ONE objectb.name = "Meera";System.out.println(a.name);   // MeeraStudent c = null;        // c points to nothingSystem.out.println(c.name);   // crash: NullPointerException

null means "this reference doesn't point to any object yet". Using the dot on null crashes with NullPointerException, the single most common runtime error in Java. When you see it, find the variable that is null on that line.

7. Two promises kept

In Session 3 we said String has a capital S for a reason. Now we know: String is a class, just like Student. Every piece of text is a String object. That's why we call methods on it with a dot: name.length() asks that String object for its length, exactly like s1.hasPassed() asks a Student. And it's why String variables can be null, while an int can never be.

Where we first promised this (Session 3)

In Session 6 we promised to explain new Scanner(System.in). Now it's clear: Scanner is a class that someone at Java wrote to read input. new Scanner(System.in) creates a Scanner object, and System.in tells it to read from the keyboard. Then we call its methods on that object: sc.nextLine(), sc.nextInt(). Just as s1.printDetails() asks one Student to do something, sc.nextLine() asks this Scanner object to read a line.

Where we first promised this (Session 6)

8. Reading input with Scanner

Java
import java.util.Scanner;public class Main {    public static void main(String[] args) {        Scanner sc = new Scanner(System.in);        System.out.print("Name: ");        String name = sc.nextLine();       // reads a whole line        System.out.print("Age: ");        int age = sc.nextInt();            // reads one int        System.out.print("Height in m: ");        double h = sc.nextDouble();        System.out.println(name + ", " + age + ", " + h);    }}

Method

Reads

nextLine()

Everything up to Enter, as a String

next()

One word (up to a space)

nextInt(), nextDouble(), nextLong(), nextBoolean()

One value of that type

hasNextInt()

Checks whether the next input is an int, without reading it

Common mistakes: The famous nextInt / nextLine trap

Java
int age = sc.nextInt();String city = sc.nextLine();   // skipped! city is ""

nextInt() reads 21 but leaves the Enter key (\n) waiting. nextLine() then immediately reads that leftover empty line. Fix: add an extra sc.nextLine(); after nextInt(), or read every line with nextLine() and convert with Integer.parseInt.

9. Arrays of objects

Java
Student[] batch = new Student[3];    // 3 empty slots: all null!batch[0] = new Student();batch[0].name = "Riya";// batch[1].name = "X";              // NullPointerException: slot 1 has no object yet

Creating the array does not create the Student objects, it only creates slots for references.

10. Printing an object

Java
Student s = new Student();System.out.println(s);   // Student@1b6d3586 (or similar)

We will open this box properly later

Student@1b6d3586: for now, "this is Java's default way to describe an object: class name, @, then a number based on the object's identity." In later session we'll teach Java to print something meaningful, like Student{name=Riya, marks=88.5}.

Interview Questions

What is the difference between a class and an object?

A class is a blueprint or template defining fields and methods. An object is an instance of a class, created at runtime with its own copy of the instance fields.

What does the new keyword do?

It allocates memory for a new object on the heap, initialises its fields (to defaults, then runs the constructor), and returns a reference to it.

What is a NullPointerException?

A runtime exception thrown when code tries to use a reference that is null, for example calling a method or accessing a field on it.

Practice

  1. easy Create a Book class with title, author, price and pages. Create 3 books and print them with a printInfo method.

  2. easy Add a method boolean isExpensive() (price over 500) and double discountedPrice(double percent).

  3. medium Create a Rectangle class with length and width, and methods area(), perimeter() and isSquare(). Read the dimensions using Scanner.

  4. medium Create an array of 5 Student objects from user input and print the topper's name.

  5. medium Predict the output:

Java
Student x = new Student();x.marks = 50;Student y = x;y.marks = 90;Student z = new Student();z.marks = x.marks;x.marks = 10;System.out.println(x.marks + " " + y.marks + " " + z.marks);

© 2026 Rohit Parihar. All rights reserved.

RP

Discussion

?