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.
the blueprint:
Studentname = Ajay
roll = 101
name = Rahul
roll = 102
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
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));
}
}
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
| Part | What it is | Example |
| Fields (attributes) | variables that hold the object’s data | String name; int roll; |
| Methods (behaviour) | actions the object can perform | void display() |
| Constructor | special method that runs on new; same name as the class, no return type | Book(String title, double price) |
this | refers to the current object | this.title = title; |
static member | belongs to the class, shared by all objects | static int count |
Figure 2: The building blocks of a class.
new Student()creates an object in memory and gives back a reference to it.s1ands2are two separate objects with their own data.- The dot reaches into an object:
s1.nameis the field,s1.display()is the method. - Methods of the class run on that object:
s1.isTopper()uses s1’s CGPA. s3was never filled in, so it holds the defaults: 0 for numbers andnullfor the String (Lesson 11).- This also explains
staticfrom Lesson 25:mainand 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) ⬅ aliasalias = 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
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);
}
}
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
newis used. this.title = title;:this.titleis the object’s field and plaintitleis the parameter.thismeans “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 countbelongs 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
| Modifier | Visible from |
private | inside the same class only |
| (none) | the same package |
protected | same package and subclasses |
public | everywhere |
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
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);
}
}
balance = 1500.0
withdraw 2000 ok? false
withdraw 300 ok? true
balance = 1200.0
Account@5e2de80c
- The balance can only change through
depositandwithdraw, which refuse bad amounts. Outside code can read it through the gettergetBalance(). - 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 owntoString()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;
}
}
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();
}
}
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();
}
}
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 fromnew(Lesson 23 showed the sameNullPointerExceptionwith Strings).
⚠️ Common Mistakes
| Mistake | Problem | Fix |
|---|---|---|
Declaring Student s; and using it | No object yet (null) | Student s = new Student(); |
| Giving a constructor a return type | It becomes an ordinary method | No return type, same name as the class |
Parameter with the same name as a field and no this | Assigns the parameter to itself | this.name = name; |
| Making every field public | Any code can break the data | Use private plus getters and setters |
Calling an instance method from main without an object | non-static method error | Create an object first |
Expecting alias = s1 to copy the object | Copies only the reference | Create 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.
thisrefers to the current object. staticmembers 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 aRectangleclass with width and height, a constructor and methodsarea()andperimeter(). (2) Add astaticcounter to count how many Rectangle objects have been created. (3) Make the fields ofStudentprivate and add getters and setters. The setter for CGPA should reject values above 10. (4) Why doesthis.name = name;needthis? (5) Explain what happens in memory when you writeStudent alias = s1;.
All 30 lessons in this series (open course page)
Module 1 · Getting Started
- Lesson 1: What is Java? Features and Uses
- Lesson 2: Installing the JDK and Running Your First Program
- Lesson 3: JDK, JRE, JVM and WORA Explained
- Lesson 4: JVM Architecture and JIT Compilation
- Lesson 5: Hello World Program Explained Line by Line
Module 2 · Building Blocks
- Lesson 6: Comments, Identifiers and Keywords
- Lesson 7: Variables and Literals
- Lesson 8: Primitive Data Types in Java
- Lesson 9: Type Conversion and Casting
- Lesson 10: Taking Input with the Scanner Class
- Lesson 11: Escape Characters and Variable Scope in Java
Module 3 · Operators
- Lesson 12: Arithmetic Operators and Increment/Decrement in Java
- Lesson 13: Relational and Logical Operators in Java
- Lesson 14: Bitwise and Shift Operators in Java
- Lesson 15: Assignment, Ternary Operator and Operator Precedence in Java
Module 4 · Control Flow
- Lesson 16: if, if-else and else-if Ladder in Java
- Lesson 17: switch Statement in Java (Classic and Modern)
- Lesson 18: while and do-while Loops in Java
- Lesson 19: for Loop and Nested Loops (Patterns) in Java
- Lesson 20: break, continue and Labelled Loops in Java
Module 5 · Data and Methods
- Lesson 21: Arrays in Java (One-Dimensional)
- Lesson 22: Multidimensional Arrays in Java
- Lesson 23: Strings and the String Pool in Java
- Lesson 24: String Methods and StringBuilder in Java
- Lesson 25: Methods and Method Overloading in Java
- Lesson 26: Recursion Basics in Java
- Lesson 27: ArrayList and Wrapper Classes in Java
- Lesson 28: Exception Handling Basics in Java