Classes & Objects in Java
Learn how to create blueprints and build things from them
💡 Think of a class like a cookie cutter and objects like the cookies! The cookie cutter (class) is the template that shows the shape, and you can use it to make many cookies (objects). Each cookie is real and can be eaten, but the cookie cutter is just the pattern!
🏗️ What is a Class?
A class is a blueprint or template for creating objects. It defines what properties (data) and behaviors (methods) the objects will have.
// This is a class - a blueprint for creating Dog objectspublic class Dog { // Fields (Properties) - what a dog knows/has String name; int age; String breed; // Constructor - how to create a new dog public Dog(String dogName, int dogAge, String dogBreed) { name = dogName; age = dogAge; breed = dogBreed; } // Methods (Behaviors) - what a dog can do public void bark() { System.out.println(name + " says: Woof! Woof!"); } public void sleep() { System.out.println(name + " is sleeping... Zzz"); }}🎯 What is an Object?
An object is a real instance created from a class. It's like a physical thing you can use and interact with!
public class CreatingObjects { public static void main(String[] args) { // Creating objects from the Dog class // Each object is a real dog with its own properties! // Object 1: Buddy Dog myDog = new Dog("Buddy", 3, "Golden Retriever"); // Object 2: Max Dog yourDog = new Dog("Max", 5, "Labrador"); // Object 3: Luna Dog friendDog = new Dog("Luna", 2, "Poodle"); // Each dog can do things (call methods) myDog.bark(); // Buddy says: Woof! Woof! yourDog.bark(); // Max says: Woof! Woof! friendDog.sleep(); // Luna is sleeping... Zzz // Each dog has its own properties System.out.println(myDog.name + " is " + myDog.age + " years old"); System.out.println(yourDog.name + " is a " + yourDog.breed); }}🔍 Anatomy of a Class
Every class has important parts that work together:
Class Name
The name that identifies your blueprint (starts with capital letter)
Fields/Properties
Variables that store the object's data (what it knows)
Constructor
Special method that creates and initializes new objects
Methods
Functions that define the object's behavior (what it can do)
public class Student { // ① Class Name // ② Fields/Properties (what the student knows/has) private String name; private int age; private double gpa; private String studentId; // ③ Constructor (how to create a student) public Student(String name, int age, String id) { this.name = name; // 'this' means "this object's" this.age = age; this.gpa = 0.0; // Default GPA this.studentId = id; } // ④ Methods (what the student can do) public void study(String subject) { System.out.println(name + " is studying " + subject); } public void takeExam() { System.out.println(name + " is taking an exam"); } public void updateGPA(double newGPA) { this.gpa = newGPA; System.out.println(name + "'s GPA updated to: " + gpa); } // Method to get information public String getInfo() { return "Student: " + name + ", Age: " + age + ", ID: " + studentId; }}🌟 Real-World Example: Bank Account
public class BankAccount { // Properties private String accountNumber; private String ownerName; private double balance; // Constructor public BankAccount(String number, String owner, double initialBalance) { this.accountNumber = number; this.ownerName = owner; this.balance = initialBalance; } // Behaviors public void deposit(double amount) { if (amount > 0) { balance += amount; System.out.println("Deposited $" + amount); System.out.println("New balance: $" + balance); } } public void withdraw(double amount) { if (amount > 0 && amount <= balance) { balance -= amount; System.out.println("Withdrew $" + amount); System.out.println("New balance: $" + balance); } else { System.out.println("Insufficient funds!"); } } public double getBalance() { return balance; } public void printAccountInfo() { System.out.println("Account: " + accountNumber); System.out.println("Owner: " + ownerName); System.out.println("Balance: $" + balance); }}// Using the BankAccount classclass BankDemo { public static void main(String[] args) { // Create two different bank accounts BankAccount account1 = new BankAccount("ACC001", "Alice", 1000.0); BankAccount account2 = new BankAccount("ACC002", "Bob", 500.0); // Alice's transactions account1.deposit(200); // Alice deposits $200 account1.withdraw(150); // Alice withdraws $150 // Bob's transactions account2.deposit(300); // Bob deposits $300 // Each account has its own balance! account1.printAccountInfo(); account2.printAccountInfo(); }}🔑 Key Concepts
Class vs Object
Class is the blueprint, Object is the actual thing made from it
Class: Car blueprint | Objects: Your red Toyota, my blue Honda
Constructor
Special method called when creating new objects
new Dog("Buddy") - creates a Dog object named Buddy
this Keyword
Refers to the current object
this.name means 'this object's name'
Multiple Objects
You can create many objects from one class
One Student class can create 100 different student objects
🔀 Constructor Overloading
public class Book { private String title; private String author; private int pages; private double price; // Constructor 1: All parameters public Book(String title, String author, int pages, double price) { this.title = title; this.author = author; this.pages = pages; this.price = price; } // Constructor 2: Without price (defaults to 0) public Book(String title, String author, int pages) { this.title = title; this.author = author; this.pages = pages; this.price = 0.0; // Default price } // Constructor 3: Just title and author public Book(String title, String author) { this.title = title; this.author = author; this.pages = 0; // Default pages this.price = 0.0; // Default price } public void displayInfo() { System.out.println("Title: " + title); System.out.println("Author: " + author); System.out.println("Pages: " + pages); System.out.println("Price: $" + price); }}class BookDemo { public static void main(String[] args) { // Using different constructors Book book1 = new Book("Java Basics", "John Doe", 300, 29.99); Book book2 = new Book("Python Guide", "Jane Smith", 250); Book book3 = new Book("C++ Intro", "Bob Johnson"); book1.displayInfo(); System.out.println(); book2.displayInfo(); System.out.println(); book3.displayInfo(); }}✨ Best Practices
- ✓Use meaningful class names that describe what they represent
- ✓Follow naming convention: Class names start with uppercase letter
- ✓Keep classes focused on one main responsibility
- ✓Initialize all fields in the constructor
- ✓Use private fields and public methods (we'll learn why in Encapsulation!)
💼 Interview Tips
- •Understand the difference between class and object clearly
- •Know that classes are reference types (stored in heap memory)
- •Remember that each object has its own copy of instance variables
- •Be able to explain what 'this' keyword does
- •Understand constructor chaining and overloading