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:
-
In IntelliJ, create a new Java project. Inside the
srcfolder, create two files:Student.javaandMain.java. -
Each class goes in its own file, and the file name must match the class name.
-
Class names use PascalCase: every word capitalised (
Student,BankAccount).
Main.java holds our starting point:
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
// 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
// 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.nameis s1's name,s1.printDetails()asks s1 to run its method. -
Inside
printDetails,namerefers to the name of whichever object the method was called on. The same method prints Riya for s1 and Kabir for s2.
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
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: NullPointerExceptionnull 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
Stringhas a capital S for a reason. Now we know:Stringis a class, just likeStudent. 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 likes1.hasPassed()asks a Student. And it's whyStringvariables can benull, while anintcan never be.
In Session 6 we promised to explain
new Scanner(System.in). Now it's clear:Scanneris a class that someone at Java wrote to read input.new Scanner(System.in)creates a Scanner object, andSystem.intells it to read from the keyboard. Then we call its methods on that object:sc.nextLine(),sc.nextInt(). Just ass1.printDetails()asks one Student to do something,sc.nextLine()asks this Scanner object to read a line.
8. Reading input with Scanner
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 |
|---|---|
|
|
Everything up to Enter, as a String |
|
|
One word (up to a space) |
|
|
One value of that type |
|
|
Checks whether the next input is an int, without reading it |
Common mistakes: The famous nextInt / nextLine trap
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
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 yetCreating the array does not create the Student objects, it only creates slots for references.
10. Printing an object
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, likeStudent{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
-
easy Create a
Bookclass with title, author, price and pages. Create 3 books and print them with aprintInfomethod. -
easy Add a method
boolean isExpensive()(price over 500) anddouble discountedPrice(double percent). -
medium Create a
Rectangleclass with length and width, and methodsarea(),perimeter()andisSquare(). Read the dimensions using Scanner. -
medium Create an array of 5
Studentobjects from user input and print the topper's name. -
medium Predict the output:
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);


Discussion