Java Classes and Objects: OOP Beginner Guide with Examples (2026)
⏱️ Reading Time: 30 minutes | 🎯 Difficulty: Beginner | 🔄 Last Updated: August 21, 2026
Table of Contents
What is Object-Oriented Programming?
Object-Oriented Programming (OOP) is a programming paradigm that organizes software design around data (objects) rather than functions and logic. An object is a self-contained unit that contains both data (attributes) and procedures (methods) to manipulate that data.
Think of OOP as modeling the real world in code:
- A Car class defines what every car has (color, speed, fuel) and what it can do (accelerate, brake, honk)
- A BankAccount class defines what every account has (balance, holder name, number) and what it can do (deposit, withdraw, transfer)
- A Student class defines what every student has (name, roll number, marks) and what they can do (study, take exam, view result)
Java is a purely object-oriented language — everything in Java revolves around classes and objects. Even the main() method lives inside a class.
The Four Pillars of OOP
| Pillar | What It Means | Analogy |
|---|---|---|
| Encapsulation | Bundling data and methods together; hiding internal details | A TV remote — you press buttons, but internal circuitry is hidden |
| Inheritance | A class derives properties from another class | A child inherits traits from parents |
| Polymorphism | Same action behaves differently based on the object | A "draw" method draws a circle for a Circle object, a square for a Square object |
| Abstraction | Showing only essential features, hiding complexity | A car dashboard shows speed and fuel, not engine piston movement |
Note: This tutorial covers Classes, Objects, Constructors, and related keywords. Encapsulation, Inheritance, Polymorphism, and Abstraction are covered in upcoming modules.
Why Do We Need OOP?
"I once wrote a 2000-line program with variables scattered everywhere. When my manager asked me to add a new feature, I spent two days afraid to touch any line because everything was connected to everything. OOP saved my sanity." — Every developer who discovered classes.
Before OOP, programs were written as a sequence of procedures (procedural programming). As programs grew, this became unmanageable. OOP solves this by:
| Problem | OOP Solution |
|---|---|
| Code repetition | Reuse classes across projects |
| Spaghetti code | Organize code into logical, self-contained units |
| Global variable chaos | Each object manages its own data |
| Team collaboration | Different developers work on different classes |
| Maintenance nightmare | Change one class without breaking the entire system |
| Real-world modeling | Code mirrors how we think about the world |
Real-world applications built with OOP:
- Android Apps: Every screen (Activity) is a class, every button is an object
- Banking Systems: Account, Transaction, Customer classes
- E-commerce: Product, Cart, Order, Payment classes
- Games: Player, Enemy, Weapon, Level classes
- Social Media: User, Post, Comment, Notification classes
What is a Class?
A class is a blueprint or template that defines what an object will contain. It specifies the attributes (data/variables) and behaviors (methods) that every object of that type will have.
Syntax
1class ClassName { 2 // Variables (Attributes / Fields / Instance Variables) 3 dataType variableName; 4 5 // Methods (Behaviors) 6 returnType methodName(parameters) { 7 // method body 8 } 9}
Example: Student Class
1class Student { 2 // Attributes 3 String name; 4 int rollNumber; 5 double marks; 6 7 // Behavior 8 void study() { 9 System.out.println(name + " is studying."); 10 } 11 12 void displayResult() { 13 System.out.println(name + " scored " + marks + " marks."); 14 } 15}
The Student class is just a blueprint. It does not occupy memory for student data yet. It only defines what a student object will have and what it can do.
What is an Object?
An object is a real instance of a class. While a class is the blueprint, an object is the actual house built from that blueprint. Objects occupy memory and hold actual values.
Creating an Object
1Student student1 = new Student();
Let us break this down:
| Part | Meaning |
|---|---|
Student | The class name (the type) |
student1 | The reference variable (like a remote control pointing to the object) |
new | Keyword that allocates memory in the heap |
Student() | The constructor call (initializes the object) |
Memory Visualization
Stack Memory Heap Memory
┌──────────┐ ┌─────────────────────┐
│ student1 │───────→ │ Student Object │
│ (ref) │ │ name = null │
└──────────┘ │ rollNumber = 0 │
│ marks = 0.0 │
└─────────────────────┘
Complete Example: Class + Object
1public class StudentDemo { 2 public static void main(String[] args) { 3 // Creating objects 4 Student student1 = new Student(); 5 Student student2 = new Student(); 6 7 // Setting attributes for student1 8 student1.name = "Ankit"; 9 student1.rollNumber = 101; 10 student1.marks = 85.5; 11 12 // Setting attributes for student2 13 student2.name = "Priya"; 14 student2.rollNumber = 102; 15 student2.marks = 92.0; 16 17 // Calling methods 18 student1.study(); // Ankit is studying. 19 student1.displayResult(); // Ankit scored 85.5 marks. 20 21 student2.study(); // Priya is studying. 22 student2.displayResult(); // Priya scored 92.0 marks. 23 } 24} 25 26class Student { 27 String name; 28 int rollNumber; 29 double marks; 30 31 void study() { 32 System.out.println(name + " is studying."); 33 } 34 35 void displayResult() { 36 System.out.println(name + " scored " + marks + " marks."); 37 } 38}
Output:
1Ankit is studying. 2Ankit scored 85.5 marks. 3Priya is studying. 4Priya scored 92.0 marks.
Key Insight:
student1andstudent2are independent objects. Changingstudent1.namedoes not affectstudent2.name. Each object has its own copy of instance variables.
Creating Classes and Objects
The new Keyword Deep Dive
When you write new Student(), Java performs three operations:
- Allocates memory in the heap for the object
- Initializes instance variables to default values (0, null, false)
- Calls the constructor to set up the object
Default Values for Instance Variables
| Data Type | Default Value |
|---|---|
byte, short, int, long | 0 |
float, double | 0.0 |
boolean | false |
char | \u0000 (null character) |
| Any object (String, etc.) | null |
Multiple Objects from One Class
1class Car { 2 String brand; 3 String color; 4 int speed; 5 6 void accelerate() { 7 speed += 10; 8 System.out.println(brand + " accelerated to " + speed + " km/h"); 9 } 10} 11 12public class CarDemo { 13 public static void main(String[] args) { 14 Car car1 = new Car(); 15 car1.brand = "Toyota"; 16 car1.color = "Red"; 17 car1.speed = 0; 18 19 Car car2 = new Car(); 20 car2.brand = "BMW"; 21 car2.color = "Black"; 22 car2.speed = 20; 23 24 car1.accelerate(); // Toyota accelerated to 10 km/h 25 car2.accelerate(); // BMW accelerated to 30 km/h 26 } 27}
Constructors
A constructor is a special method that runs automatically when an object is created. Its job is to initialize the object with valid starting values.
Characteristics of Constructors
- Same name as the class
- No return type (not even
void) - Automatically called with
new - Can have parameters (parameterized constructor)
- Can be overloaded (multiple constructors)
Default Constructor
If you do not write any constructor, Java provides a default no-arg constructor automatically.
1class Student { 2 String name; 3 int age; 4 5 // Java provides this automatically if you do not write any constructor: 6 // Student() { } 7} 8 9Student s = new Student(); // Uses default constructor
Custom Default Constructor
1class Student { 2 String name; 3 int age; 4 5 // Custom default constructor 6 Student() { 7 name = "Unknown"; 8 age = 0; 9 System.out.println("Student object created with defaults!"); 10 } 11} 12 13// Usage 14Student s = new Student(); // Prints: Student object created with defaults! 15System.out.println(s.name); // Unknown
Parameterized Constructor
1class Student { 2 String name; 3 int rollNumber; 4 double marks; 5 6 // Parameterized constructor 7 Student(String name, int rollNumber, double marks) { 8 this.name = name; 9 this.rollNumber = rollNumber; 10 this.marks = marks; 11 } 12 13 void display() { 14 System.out.println("Name: " + name); 15 System.out.println("Roll: " + rollNumber); 16 System.out.println("Marks: " + marks); 17 } 18} 19 20public class ConstructorDemo { 21 public static void main(String[] args) { 22 Student s = new Student("Rahul", 101, 88.5); 23 s.display(); 24 } 25}
Output:
1Name: Rahul 2Roll: 101 3Marks: 88.5
Constructor Overloading
A class can have multiple constructors with different parameter lists:
1class Student { 2 String name; 3 int rollNumber; 4 double marks; 5 6 // No-arg constructor 7 Student() { 8 this.name = "Unknown"; 9 this.rollNumber = 0; 10 this.marks = 0.0; 11 } 12 13 // Constructor with name only 14 Student(String name) { 15 this.name = name; 16 this.rollNumber = 0; 17 this.marks = 0.0; 18 } 19 20 // Constructor with all fields 21 Student(String name, int rollNumber, double marks) { 22 this.name = name; 23 this.rollNumber = rollNumber; 24 this.marks = marks; 25 } 26} 27 28// Usage 29Student s1 = new Student(); // Unknown, 0, 0.0 30Student s2 = new Student("Ankit"); // Ankit, 0, 0.0 31Student s3 = new Student("Priya", 102, 91.0); // Priya, 102, 91.0
The this Keyword
The this keyword is a reference to the current object — the object whose method or constructor is being called.
Use Case 1: Resolve Name Conflict
When constructor parameters have the same name as instance variables, this tells Java which is which:
1class Student { 2 String name; 3 int age; 4 5 Student(String name, int age) { 6 this.name = name; // this.name = instance variable 7 this.age = age; // name = parameter 8 } 9}
Without this, Java cannot distinguish between the parameter and the instance variable:
1// WRONG — Both refer to the parameter, instance variables stay null/0! 2Student(String name, int age) { 3 name = name; // Parameter assigned to itself! 4 age = age; // Parameter assigned to itself! 5}
Use Case 2: Constructor Chaining
One constructor can call another constructor using this():
1class Student { 2 String name; 3 int age; 4 String course; 5 6 // Main constructor 7 Student(String name, int age, String course) { 8 this.name = name; 9 this.age = age; 10 this.course = course; 11 } 12 13 // Delegates to main constructor with default course 14 Student(String name, int age) { 15 this(name, age, "Computer Science"); 16 } 17 18 // Delegates with defaults 19 Student() { 20 this("Unknown", 18, "General"); 21 } 22} 23 24// Usage 25Student s1 = new Student("Rahul", 20, "Mathematics"); 26Student s2 = new Student("Ankit", 21); // Course = "Computer Science" 27Student s3 = new Student(); // All defaults
Rule:
this()must be the first statement in the constructor.
Use Case 3: Pass Current Object to Another Method
1class Student { 2 String name; 3 4 void enroll(Course course) { 5 course.addStudent(this); // Passes current Student object 6 } 7}
The static Keyword
The static keyword means "belongs to the class, not to any specific object." Static members are shared by all instances of the class.
Static Variables (Class Variables)
1class Student { 2 String name; // Instance variable — each object has its own copy 3 static String college; // Static variable — shared by ALL students 4 5 Student(String name) { 6 this.name = name; 7 } 8} 9 10// Usage 11Student.college = "Tech University"; // Set once for all students 12 13Student s1 = new Student("Ankit"); 14Student s2 = new Student("Priya"); 15 16System.out.println(s1.college); // Tech University 17System.out.println(s2.college); // Tech University 18 19Student.college = "IIT Bombay"; // Changes for ALL students 20System.out.println(s1.college); // IIT Bombay
Static Methods
Static methods belong to the class and can be called without creating an object:
1class MathUtility { 2 static int square(int number) { 3 return number * number; 4 } 5 6 static double circleArea(double radius) { 7 return Math.PI * radius * radius; 8 } 9} 10 11// Call directly on the class — no object needed! 12System.out.println(MathUtility.square(5)); // 25 13System.out.println(MathUtility.circleArea(3.0)); // 28.27
Important: Static methods cannot directly access instance variables or instance methods because there is no
thisreference.
Static Block
A static block runs once when the class is loaded into memory, before any objects are created:
1class DatabaseConfig { 2 static String url; 3 static String username; 4 5 static { 6 System.out.println("Loading database configuration..."); 7 url = "jdbc:mysql://localhost:3306/mydb"; 8 username = "admin"; 9 } 10} 11 12// When you first use the class: 13System.out.println(DatabaseConfig.url); // Static block runs first!
Static vs Instance Members
| Feature | Instance | Static |
|---|---|---|
| Belongs to | Object | Class |
| Memory | Created per object | Created once |
| Access | object.variable | ClassName.variable |
| Shared? | No — each object has its own | Yes — all objects share |
Can access this? | Yes | No |
The final Keyword
The final keyword means "cannot be changed." It can be applied to variables, methods, and classes.
Final Variables (Constants)
1class Circle { 2 final double PI = 3.14159; // Cannot be reassigned! 3 4 void demonstrate() { 5 // PI = 3.14; // ❌ Compilation error! 6 System.out.println("PI = " + PI); 7 } 8}
Convention: Final variables are written in
UPPER_CASEwith underscores.
1class Constants { 2 static final double PI = 3.14159; 3 static final int MAX_USERS = 1000; 4 static final String APP_NAME = "Tech3Space Portal"; 5}
Final Methods
A final method cannot be overridden by subclasses:
1class Animal { 2 final void makeSound() { 3 System.out.println("Animal makes a sound"); 4 } 5} 6 7class Dog extends Animal { 8 // void makeSound() { } // ❌ Compilation error! Cannot override final method 9}
Final Classes
A final class cannot be inherited (extended):
1final class SecurityManager { 2 // This class cannot be subclassed 3} 4 5// class MySecurityManager extends SecurityManager { } // ❌ Error!
Real-world example:
java.lang.Stringis afinalclass. No one can create a malicious subclass of String.
Access Modifiers
Access modifiers control who can see and use your classes, methods, and variables. They are the foundation of encapsulation.
The Four Access Levels
| Modifier | Same Class | Same Package | Subclass (Different Package) | Other Package |
|---|---|---|---|---|
public | ✅ | ✅ | ✅ | ✅ |
protected | ✅ | ✅ | ✅ | ❌ |
| Default (no modifier) | ✅ | ✅ | ❌ | ❌ |
private | ✅ | ❌ | ❌ | ❌ |
Visual Analogy
Think of access modifiers as security levels in a building:
private— Your personal diary. Only you can read it.- Default — Your apartment. Neighbors in the same building can visit.
protected— Your family home. Family members (even living elsewhere) can visit.public— A public park. Anyone can enter.
Examples
1public class BankAccount { 2 private double balance; // Only this class can access 3 protected String accountType; // Subclasses can access 4 String branchCode; // Same package classes can access 5 public String accountHolder; // Anyone can access 6 7 private void updateLedger() { // Internal method 8 // Only BankAccount can call this 9 } 10 11 public void deposit(double amount) { // External interface 12 balance += amount; 13 } 14 15 public double getBalance() { // Controlled read access 16 return balance; 17 } 18}
Best Practice: Make fields
privateand providepublicgetter/setter methods. This is encapsulation in action.
Packages in Java
A package is a namespace that organizes related classes and prevents naming conflicts. It is like a folder structure for your code.
Why Packages Matter
| Without Packages | With Packages |
|---|---|
| All classes in one flat space | Logical grouping (model, service, controller) |
Name collisions (two User classes) | com.company.model.User vs com.company.service.User |
| No access control boundaries | Default access works within package |
| Hard to navigate | Clear project structure |
Creating a Package
1package com.tech3space.student; 2 3public class Student { 4 // Class code 5}
The package declaration must be the first line in the file.
Importing Classes
1// Import a specific class 2import java.util.Scanner; 3import java.util.ArrayList; 4 5// Import all classes from a package 6import java.util.*; 7 8// Import a custom package class 9import com.tech3space.student.Student;
Tip: Import specific classes rather than using
*for better readability and faster compilation.
Package Naming Convention
Packages follow reverse domain name convention:
- Company:
tech3space.com→ Package:com.tech3space - Project:
com.tech3space.ecommerce - Module:
com.tech3space.ecommerce.model - Class:
com.tech3space.ecommerce.model.Product
Object Lifecycle in Java
Understanding how objects are born, live, and die is crucial for writing efficient Java programs.
The Lifecycle Stages
1. CLASS LOADING
↓ JVM loads the .class file into memory
2. OBJECT CREATION
↓ new keyword allocates heap memory
3. CONSTRUCTOR EXECUTION
↓ Object is initialized with values
4. OBJECT IN USE
↓ Methods are called, data is processed
5. OBJECT ELIGIBLE FOR GC
↓ No more references point to the object
6. GARBAGE COLLECTION
↓ JVM reclaims memory
Example
1public class LifecycleDemo { 2 public static void main(String[] args) { 3 // Stage 2-3: Creation + Constructor 4 Student s1 = new Student("Ankit", 101); 5 6 // Stage 4: In use 7 s1.study(); 8 9 // Stage 5: Eligible for GC 10 s1 = null; // No reference points to the object anymore 11 12 // Stage 6: GC runs (eventually, not guaranteed immediately) 13 System.gc(); // Suggest GC (JVM decides when to actually run) 14 } 15}
Real-World Use Cases
Use Case 1: E-Commerce Product Catalog
1class Product { 2 private int id; 3 private String name; 4 private double price; 5 private int stock; 6 7 Product(int id, String name, double price, int stock) { 8 this.id = id; 9 this.name = name; 10 this.price = price; 11 this.stock = stock; 12 } 13 14 public boolean isAvailable() { 15 return stock > 0; 16 } 17 18 public void display() { 19 System.out.printf("%d: %s - $%.2f (%d in stock)%n", 20 id, name, price, stock); 21 } 22} 23 24public class ProductCatalog { 25 public static void main(String[] args) { 26 Product p1 = new Product(101, "Wireless Mouse", 29.99, 50); 27 Product p2 = new Product(102, "Mechanical Keyboard", 89.99, 0); 28 29 p1.display(); 30 p2.display(); 31 32 System.out.println("Mouse available? " + p1.isAvailable()); // true 33 System.out.println("Keyboard available? " + p2.isAvailable()); // false 34 } 35}
Use Case 2: Bank Account with Business Rules
1class BankAccount { 2 private static final double MIN_BALANCE = 500.0; 3 4 private String accountHolder; 5 private String accountNumber; 6 private double balance; 7 8 BankAccount(String holder, String number, double initialDeposit) { 9 this.accountHolder = holder; 10 this.accountNumber = number; 11 this.balance = initialDeposit; 12 } 13 14 public void deposit(double amount) { 15 if (amount > 0) { 16 balance += amount; 17 System.out.println("Deposited: $" + amount); 18 } else { 19 System.out.println("Invalid deposit amount"); 20 } 21 } 22 23 public void withdraw(double amount) { 24 if (amount <= 0) { 25 System.out.println("Invalid amount"); 26 } else if (balance - amount < MIN_BALANCE) { 27 System.out.println("Cannot withdraw. Minimum balance of $" + MIN_BALANCE + " required."); 28 } else { 29 balance -= amount; 30 System.out.println("Withdrawn: $" + amount); 31 } 32 } 33 34 public void display() { 35 System.out.println("Account: " + accountNumber); 36 System.out.println("Holder: " + accountHolder); 37 System.out.println("Balance: $" + balance); 38 } 39}
Common Mistakes
Mistake 1: Forgetting new
1// WRONG — Creates a null reference, not an object! 2Student s; 3s.name = "Ankit"; // ❌ NullPointerException! 4 5// CORRECT 6Student s = new Student(); 7s.name = "Ankit"; // ✅ Works
Mistake 2: Constructor Name Mismatch
1// WRONG — This is a method, not a constructor! 2class Student { 3 void Student() { // ❌ Has return type (void) — not a constructor! 4 System.out.println("This is a method, not a constructor!"); 5 } 6} 7 8// CORRECT 9class Student { 10 Student() { // ✅ No return type = constructor 11 System.out.println("Constructor called!"); 12 } 13}
Mistake 3: Shadowing Without this
1// WRONG — Parameters shadow instance variables 2class Student { 3 String name; 4 5 Student(String name, int age) { 6 name = name; // ❌ Both refer to parameter! 7 age = age; // ❌ No effect on instance variables 8 } 9} 10 11// CORRECT 12class Student { 13 String name; 14 int age; 15 16 Student(String name, int age) { 17 this.name = name; // ✅ this.name = instance, name = parameter 18 this.age = age; 19 } 20}
Mistake 4: Calling Instance Methods from Static Context
1class Demo { 2 void instanceMethod() { } 3 4 static void staticMethod() { 5 // instanceMethod(); // ❌ Compilation error! 6 // this.instanceMethod(); // ❌ 'this' does not exist in static context! 7 } 8}
Mistake 5: Modifying final Variables
1class Constants { 2 final int MAX = 100; 3 4 void change() { 5 // MAX = 200; // ❌ Compilation error! 6 } 7}
Mistake 6: Confusing Class and Object
1class Car { 2 static String brand = "Toyota"; // Class-level 3 String color; // Object-level 4} 5 6// WRONG thinking 7Car.color = "Red"; // ❌ color belongs to objects, not the class! 8 9// CORRECT 10Car c = new Car(); 11c.color = "Red"; // ✅ Each car has its own color 12Car.brand = "Honda"; // ✅ Brand is shared (static)
Best Practices
-
One class, one responsibility — A
Studentclass should handle student data, not database connections. -
Use constructors to enforce valid state — Never allow an object to exist in an invalid state.
1BankAccount(String number, double deposit) { 2 if (deposit < 0) throw new IllegalArgumentException("Deposit cannot be negative"); 3 this.balance = deposit; 4} -
Make fields private — Use getters and setters for controlled access (encapsulation).
-
Use meaningful class and variable names —
StudentnotS,accountBalancenotab. -
Use
thisconsistently — Even when not required, it improves clarity. -
Prefer
finalfor constants — Makes intent clear and prevents accidental changes. -
Keep static usage minimal — Static is for shared state and utilities, not for object data.
-
Organize classes into packages — Even small projects benefit from
model,service,utilpackages. -
Document with JavaDoc — Explain what the class represents and how to use it.
-
Avoid God classes — A class with 50 fields and 100 methods is a maintenance nightmare. Split it.
Architecture & Performance Considerations
Object Creation Cost
Creating objects with new involves:
- Memory allocation in the heap
- Zeroing memory (default initialization)
- Constructor execution
For high-performance systems (games, real-time trading), excessive object creation causes GC pressure. Solutions include:
- Object pooling: Reuse objects instead of creating new ones
- Flyweight pattern: Share common data across objects
- Primitive types: Use
intinstead ofIntegerwhere possible
Static Memory Allocation
Static variables are allocated when the class is loaded and stay in memory until the program ends. Overusing static variables can cause memory leaks because they are never garbage collected.
1// DANGEROUS — Static collection grows forever 2class Cache { 3 static List<Data> cache = new ArrayList<>(); // Never GC'd! 4}
Class Loading and Static Blocks
Classes are loaded lazily — when first referenced. Static blocks run at class load time, making them ideal for:
- Loading configuration files
- Initializing database connections
- Registering drivers
1class DatabaseConnection { 2 static { 3 try { 4 Class.forName("com.mysql.cj.jdbc.Driver"); 5 } catch (ClassNotFoundException e) { 6 throw new RuntimeException("MySQL driver not found", e); 7 } 8 } 9}
Memory Layout of Objects
In the JVM heap, each object contains:
- Object header (12-16 bytes): Mark word + class pointer
- Instance fields: Your variables
- Padding: Aligned to 8-byte boundaries
A Student object with String name and int age uses approximately 24-32 bytes of heap memory, not just the data itself.
Practice Programs
Exercise 1: Book Class
1class Book { 2 private String title; 3 private String author; 4 private double price; 5 private int pages; 6 7 Book(String title, String author, double price, int pages) { 8 this.title = title; 9 this.author = author; 10 this.price = price; 11 this.pages = pages; 12 } 13 14 void display() { 15 System.out.println("Title: " + title); 16 System.out.println("Author: " + author); 17 System.out.println("Price: $" + price); 18 System.out.println("Pages: " + pages); 19 } 20 21 boolean isExpensive() { 22 return price > 50; 23 } 24} 25 26public class BookDemo { 27 public static void main(String[] args) { 28 Book b1 = new Book("Clean Code", "Robert Martin", 45.0, 464); 29 Book b2 = new Book("Design Patterns", "Gang of Four", 55.0, 395); 30 31 b1.display(); 32 System.out.println("Expensive? " + b1.isExpensive()); 33 34 b2.display(); 35 System.out.println("Expensive? " + b2.isExpensive()); 36 } 37}
Exercise 2: Rectangle with Area and Perimeter
1class Rectangle { 2 private double length; 3 private double width; 4 5 Rectangle(double length, double width) { 6 this.length = length; 7 this.width = width; 8 } 9 10 double getArea() { 11 return length * width; 12 } 13 14 double getPerimeter() { 15 return 2 * (length + width); 16 } 17 18 boolean isSquare() { 19 return length == width; 20 } 21} 22 23public class RectangleDemo { 24 public static void main(String[] args) { 25 Rectangle r1 = new Rectangle(5, 10); 26 Rectangle r2 = new Rectangle(4, 4); 27 28 System.out.println("Rectangle 1: Area=" + r1.getArea() + ", Perimeter=" + r1.getPerimeter()); 29 System.out.println("Is square? " + r1.isSquare()); 30 31 System.out.println("Rectangle 2: Area=" + r2.getArea() + ", Perimeter=" + r2.getPerimeter()); 32 System.out.println("Is square? " + r2.isSquare()); 33 } 34}
Exercise 3: Employee with Static Counter
1class Employee { 2 private static int employeeCount = 0; 3 private int id; 4 private String name; 5 private double salary; 6 7 Employee(String name, double salary) { 8 employeeCount++; 9 this.id = employeeCount; 10 this.name = name; 11 this.salary = salary; 12 } 13 14 void display() { 15 System.out.println("ID: " + id + ", Name: " + name + ", Salary: $" + salary); 16 } 17 18 static int getEmployeeCount() { 19 return employeeCount; 20 } 21} 22 23public class EmployeeDemo { 24 public static void main(String[] args) { 25 Employee e1 = new Employee("Alice", 50000); 26 Employee e2 = new Employee("Bob", 60000); 27 Employee e3 = new Employee("Charlie", 55000); 28 29 e1.display(); 30 e2.display(); 31 e3.display(); 32 33 System.out.println("Total employees: " + Employee.getEmployeeCount()); 34 } 35}
Exercise 4: Temperature Converter
1class Temperature { 2 private double celsius; 3 4 Temperature(double celsius) { 5 this.celsius = celsius; 6 } 7 8 double toFahrenheit() { 9 return (celsius * 9 / 5) + 32; 10 } 11 12 double toKelvin() { 13 return celsius + 273.15; 14 } 15 16 void displayAll() { 17 System.out.println(celsius + "°C = " + toFahrenheit() + "°F = " + toKelvin() + "K"); 18 } 19} 20 21public class TemperatureDemo { 22 public static void main(String[] args) { 23 Temperature t1 = new Temperature(0); 24 Temperature t2 = new Temperature(100); 25 Temperature t3 = new Temperature(37); 26 27 t1.displayAll(); 28 t2.displayAll(); 29 t3.displayAll(); 30 } 31}
Exercise 5: Circle with Final PI
1class Circle { 2 private static final double PI = 3.14159; 3 private double radius; 4 5 Circle(double radius) { 6 this.radius = radius; 7 } 8 9 double getArea() { 10 return PI * radius * radius; 11 } 12 13 double getCircumference() { 14 return 2 * PI * radius; 15 } 16 17 void display() { 18 System.out.println("Radius: " + radius); 19 System.out.println("Area: " + getArea()); 20 System.out.println("Circumference: " + getCircumference()); 21 } 22} 23 24public class CircleDemo { 25 public static void main(String[] args) { 26 Circle c1 = new Circle(5); 27 Circle c2 = new Circle(10); 28 29 c1.display(); 30 c2.display(); 31 } 32}
Mini Project: Student Management System
Build a comprehensive student management system with multiple classes, constructors, static fields, and business logic.
1import java.util.Scanner; 2 3class Student { 4 private static int totalStudents = 0; 5 private static final String SCHOOL_NAME = "Tech3Space Academy"; 6 7 private int rollNumber; 8 private String name; 9 private int[] marks; 10 private String grade; 11 12 Student(String name, int[] marks) { 13 totalStudents++; 14 this.rollNumber = totalStudents; 15 this.name = name; 16 this.marks = marks.clone(); 17 calculateGrade(); 18 } 19 20 private void calculateGrade() { 21 double avg = getAverage(); 22 if (avg >= 90) grade = "A+"; 23 else if (avg >= 80) grade = "A"; 24 else if (avg >= 70) grade = "B"; 25 else if (avg >= 60) grade = "C"; 26 else if (avg >= 40) grade = "D"; 27 else grade = "F"; 28 } 29 30 double getAverage() { 31 int sum = 0; 32 for (int m : marks) sum += m; 33 return (double) sum / marks.length; 34 } 35 36 int getTotal() { 37 int sum = 0; 38 for (int m : marks) sum += m; 39 return sum; 40 } 41 42 boolean hasPassed() { 43 return !grade.equals("F"); 44 } 45 46 void displayReport() { 47 System.out.println("\n+----------------------------------------+"); 48 System.out.println("| STUDENT REPORT CARD |"); 49 System.out.println("+----------------------------------------+"); 50 System.out.println("| School: " + padRight(SCHOOL_NAME, 30) + " |"); 51 System.out.println("| Roll: " + padRight(String.valueOf(rollNumber), 30) + " |"); 52 System.out.println("| Name: " + padRight(name, 30) + " |"); 53 System.out.println("+----------------------------------------+"); 54 String[] subjects = {"Math", "Science", "English", "History", "Computer"}; 55 for (int i = 0; i < marks.length && i < subjects.length; i++) { 56 System.out.println("| " + padRight(subjects[i] + ":", 10) + padRight(String.valueOf(marks[i]), 28) + " |"); 57 } 58 System.out.println("+----------------------------------------+"); 59 System.out.println("| Total: " + padRight(String.valueOf(getTotal()), 27) + " |"); 60 System.out.println("| Average: " + padRight(String.format("%.2f", getAverage()), 27) + " |"); 61 System.out.println("| Grade: " + padRight(grade, 27) + " |"); 62 System.out.println("| Status: " + padRight(hasPassed() ? "PASSED" : "FAILED", 27) + " |"); 63 System.out.println("+----------------------------------------+"); 64 } 65 66 private String padRight(String s, int n) { 67 return String.format("%-" + n + "s", s); 68 } 69 70 static int getTotalStudents() { 71 return totalStudents; 72 } 73 74 String getName() { return name; } 75 int getRollNumber() { return rollNumber; } 76 String getGrade() { return grade; } 77} 78 79public class StudentManagementSystem { 80 public static void main(String[] args) { 81 try (Scanner input = new Scanner(System.in)) { 82 Student[] students = new Student[100]; 83 int count = 0; 84 boolean running = true; 85 86 while (running) { 87 System.out.println("\n========== STUDENT MANAGEMENT SYSTEM =========="); 88 System.out.println("1. Add Student"); 89 System.out.println("2. View All Students"); 90 System.out.println("3. View Student Report"); 91 System.out.println("4. View Class Statistics"); 92 System.out.println("5. Exit"); 93 System.out.print("Choice: "); 94 95 int choice = Integer.parseInt(input.nextLine()); 96 97 switch (choice) { 98 case 1 -> { 99 System.out.print("Enter name: "); 100 String name = input.nextLine(); 101 int[] marks = new int[5]; 102 String[] subjects = {"Math", "Science", "English", "History", "Computer"}; 103 for (int i = 0; i < 5; i++) { 104 System.out.print(subjects[i] + " marks: "); 105 marks[i] = Integer.parseInt(input.nextLine()); 106 } 107 students[count] = new Student(name, marks); 108 count++; 109 System.out.println("✅ Student added successfully!"); 110 } 111 case 2 -> { 112 System.out.println("\n--- ALL STUDENTS ---"); 113 System.out.printf("%-5s %-15s %-10s %-10s%n", "Roll", "Name", "Average", "Grade"); 114 System.out.println("-".repeat(45)); 115 for (int i = 0; i < count; i++) { 116 System.out.printf("%-5d %-15s %-10.2f %-10s%n", 117 students[i].getRollNumber(), 118 students[i].getName(), 119 students[i].getAverage(), 120 students[i].getGrade()); 121 } 122 } 123 case 3 -> { 124 System.out.print("Enter roll number: "); 125 int roll = Integer.parseInt(input.nextLine()); 126 boolean found = false; 127 for (int i = 0; i < count; i++) { 128 if (students[i].getRollNumber() == roll) { 129 students[i].displayReport(); 130 found = true; 131 break; 132 } 133 } 134 if (!found) System.out.println("❌ Student not found."); 135 } 136 case 4 -> { 137 if (count == 0) { 138 System.out.println("No students enrolled yet."); 139 continue; 140 } 141 double classAvg = 0; 142 int passed = 0; 143 for (int i = 0; i < count; i++) { 144 classAvg += students[i].getAverage(); 145 if (students[i].hasPassed()) passed++; 146 } 147 classAvg /= count; 148 System.out.println("\n--- CLASS STATISTICS ---"); 149 System.out.println("Total Students: " + Student.getTotalStudents()); 150 System.out.println("Class Average: " + String.format("%.2f", classAvg)); 151 System.out.println("Passed: " + passed + "/" + count); 152 System.out.println("Pass Rate: " + String.format("%.1f", (passed * 100.0 / count)) + "%"); 153 } 154 case 5 -> { 155 System.out.println("👋 Goodbye!"); 156 running = false; 157 } 158 default -> System.out.println("❌ Invalid choice."); 159 } 160 } 161 } 162 } 163}
What This Project Covers:
- Class design with private fields and public methods
- Parameterized constructor with validation logic
- Static fields (
totalStudents,SCHOOL_NAME) - Instance methods for business logic (
calculateGrade,getAverage,hasPassed) - Array of objects (
Student[] students) - Interactive menu with CRUD-like operations
- Formatted report card output
- Class statistics calculation
Summary & Cheat Sheet
Quick Reference
| Concept | Syntax / Usage | Notes |
|---|---|---|
| Class declaration | class Name { } | Blueprint for objects |
| Object creation | ClassName obj = new ClassName(); | Allocates memory, calls constructor |
| Constructor | ClassName(params) { } | No return type, same name as class |
| Default constructor | Provided by Java if none written | Initializes fields to defaults |
| Parameterized constructor | Student(String n, int a) { } | Custom initialization |
| Constructor overloading | Multiple constructors | Different parameter lists |
this keyword | this.field = param; | Refers to current object |
| Constructor chaining | this(params); | Must be first statement |
| Static variable | static int count; | Shared across all objects |
| Static method | static void method() { } | Called on class, not object |
| Static block | static { } | Runs once when class loads |
final variable | final int MAX = 100; | Cannot be reassigned |
final method | final void method() { } | Cannot be overridden |
final class | final class Name { } | Cannot be extended |
public | Accessible everywhere | Most permissive |
protected | Class + package + subclasses | For inheritance |
| Default | Class + package only | No keyword |
private | Class only | Most restrictive |
| Package | package com.company; | First line of file |
| Import | import java.util.Scanner; | Bring external classes |
Key Takeaways
- A class is a blueprint; an object is the actual instance.
- Constructors initialize objects. They have no return type and share the class name.
thisresolves ambiguity. Use it when parameter names match field names.- Static belongs to the class. Instance belongs to the object.
finalprevents change. Use it for constants, unoverridable methods, and secure classes.- Access modifiers control visibility. Prefer
privatefor fields,publicfor APIs. - Packages prevent chaos. Organize code logically from day one.
- Objects have a lifecycle. Created with
new, used, then garbage collected. - Never leave objects in invalid states. Validate in constructors.
- OOP mirrors reality. Design classes the way you think about real-world entities.
What's Next?
Now that you understand classes and objects, you are ready for the advanced pillars of OOP:
- Encapsulation — Getters, setters, and data hiding
- Inheritance — Reusing code through parent-child relationships
- Polymorphism — Method overriding and dynamic dispatch
- Abstraction — Abstract classes and interfaces
- Exception Handling — Making your classes robust
- Collections Framework — ArrayList, HashMap, and beyond
Classes and objects are the foundation of everything in Java. Master them, and you have unlocked the door to professional Java development.