Home/Java/Classes & Objects in Java

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.

SimpleClass.java
java
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
// This is a class - a blueprint for creating Dog objects
public 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!

CreatingObjects.java
java
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
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:

1

Class Name

The name that identifies your blueprint (starts with capital letter)

2

Fields/Properties

Variables that store the object's data (what it knows)

3

Constructor

Special method that creates and initializes new objects

4

Methods

Functions that define the object's behavior (what it can do)

CompleteClassExample.java
java
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
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

BankAccount.java
java
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
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 class
class 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

ConstructorOverloading.java
java
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
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