Skip to main content

Classes and Objects

Class

✔ A class is an expanded concept of a structure.

👉 Instead of holding only data, a class can hold both data and functions.

✔ A class contains the logical description of a real-world entity in terms of:

  • State
  • Behavior

👉 Class = State + Behavior (logical description)

✔ A class is a:

  • Prototype
  • Template
  • Pattern
  • Blueprint

of an object’s state and behavior.


Syntax

[modifiers]class <ClassName> {
// Members of class
}

Example

class Customer {

int cid;
String cname;
long phone;

void show() {
// ...
}
}

Object

✔ Object is the physical representation of a class.

✔ Object is a runtime entity because memory is allocated when the program executes based on class description.

✔ Memory for objects is allocated in the HEAP MEMORY.

✔ Object is also called an instance of a class (both terms are interchangeable).


Syntax

<ClassName><refVarName>=new <ClassName>();

Examples

C ustomerc1=new Customer();
C ustomerc2=new Customer();
C ustomerc3=new Customer();

✔ Key Concept

  • One class → can create multiple objects
  • Each object → has separate memory
  • All objects share the same class structure

💡 Quick Understanding (for CodeNBuild)

  • Class → blueprint 🧩
  • Object → real instance 🧍
  • Class = logical
  • Object = physical
  • Stored in:
    • Class → no memory for objects
    • Object → stored in heap memory

Lab286.java

class Lab286 {

public static void main(String[] args) {
C ustomerc1 = new Customer();
c1.show();

C ustomerc2 = new Customer();
c2.cid = 99;
c2.cname = "Java";
c2.phone = 657999999;
c2.show();
}
}

Customer Class

class Customer {

int cid;
String cname;
long phone;

void show() {
System.out.println(cid);
System.out.println(cname);
System.out.println(phone);
}
}

What is happening inside the JVM when you create an object

Example:

C ustomerc1=new Customer();

✔ Step-by-step Execution

1) Memory allocation for reference variable

  • JVM allocates 8 bytes for reference variable c1
  • Initializes it with null
c1 → null

2) Class loading

  • JVM checks whether the class is loaded
  • If not:
    • Loads the class
    • Allocates memory for static variables
    • Initializes them with default values

3) Object creation

  • JVM creates the object in heap memory
  • Allocates memory for instance variables
  • Initializes with default values:
cid = 0
cname = null
phone = 0

4) Assign reference

  • Address of the newly created object is assigned to c1
c1 → (object address)

💡 Quick Understanding (for CodeNBuild)

  • c1 → reference variable (stack memory)
  • Object → stored in heap memory
  • Default values:
    • int → 0
    • String → null
    • long → 0