What is a Class?
About
A class in Java is a blueprint or template for creating objects. It defines the state (fields/attributes) and behavior (methods) that objects of that class will have.
Characteristics of a Class
1. Defines State (Attributes)
Represented by fields/variables inside the class.
Example:
String name;
,int age;
.
2. Defines Behavior (Methods)
Defined by functions inside the class.
Example:
void eat() {}
,void sleep() {}
.
3. Can Contain a Constructor
Special method used to initialize an object.
Example:
Person(String name, int age) { this.name = name; this.age = age; }
.
4. Objects are Created from a Class
A class itself is just a definition; actual objects are instantiated from it.
Example of a Class in Java
How Classes Work in Memory
The class definition itself is stored in method area (Metaspace in Java 8+).
When an object is created, memory is allocated in the heap, and the reference variable (like
person1
) is stored in the stack.
Last updated
Was this helpful?