Classes and Objects in Java

Java is an Object-Oriented Programming (OOP) language. Classes and objects are two fundamental concepts of OOP. A class defines the structure and behaviour, while an object is an instance created from that class.

1. What is a Class?

A class is a blueprint or template used to create objects. It defines the properties (variables) and behaviours (methods) that its objects can have.

For example, consider a Bank Account. Every account has an account holder name, account number, and balance. It can also perform operations like depositing and withdrawing money.

class BankAccount { String accountHolder; int accountNumber; double balance; void deposit(double amount) { balance += amount; } void checkBalance() { System.out.println(balance); } } 

Here, BankAccount is a class that defines the properties and behaviours of a bank account.

2. What is an Object?

An object is an instance of a class. We create objects using the new keyword.

Syntax:

ClassName objectName = new ClassName(); 

For example:

BankAccount customer1 = new BankAccount(); customer1.accountHolder = "Arun"; customer1.accountNumber = 101; customer1.balance = 5000; customer1.deposit(2000); customer1.checkBalance(); 

Here, customer1 is an object reference variable that refers to the newly created BankAccount object.

We can create multiple objects from the same class, and each object maintains its own instance variable values.

BankAccount customer2 = new BankAccount(); customer2.accountHolder = "Kumar"; customer2.accountNumber = 102; customer2.balance = 10000; 

Both customers use the same class, but their account information is different.

3. What Happens When We Create an Object?

When we create an object using the new keyword, Java performs several operations behind the scenes.

BankAccount customer1 = new BankAccount(); 

The following steps take place:

  1. Memory Allocation: Java allocates memory for the new object in Heap memory.
  2. Default Values: Instance variables receive their default values, such as 0 for integers and null for reference types.
  3. Constructor Execution: The constructor executes to initialize the object. If no constructor is declared, Java provides a default no-argument constructor.
  4. Reference Creation: The new expression returns a reference to the newly created object.
  5. Object Access: We use the reference variable to access the object's variables and methods.

Stack and Heap Memory

Java uses different memory areas to manage objects and local variables.

  • Stack Memory: Stores local variables and object reference variables within method execution.
  • Heap Memory: Stores objects and their instance variables.

For example:

Student s1 = new Student(); 

Here, the reference variable s1 is stored in the stack frame of the executing method, while the actual Student object is allocated in Heap memory.