Short Answer:
The basic building blocks of a Java class are Variables, Methods, Constructors, Blocks, and Nested Classes.
Detailed Explanation:
A Java class is a blueprint for creating objects. It contains state (data) and behavior (methods). Below are the main components:
1. Variables (Fields)
Used to store data inside a class.
- Instance variables
- Static variables
- Local variables
2. Methods
Define behavior or actions that objects can perform.
3. Constructors
Special methods used to initialize objects. Constructor name must be same as class name.
4. Blocks
- Static Block – Executes once when class loads
- Instance Block – Executes before constructor
5. Nested Classes
A class defined inside another class.
Example
class Student {
// 1. Variable
String name;
// 2. Static Block
static {
System.out.println("Class Loaded");
}
// 3. Constructor
Student(String name) {
this.name = name;
}
// 4. Method
void display() {
System.out.println("Name: " + name);
}
}
Important Interview Points
- Class contains state + behavior.
- Constructor is not a method.
- Static members belong to class, non-static belong to object.
- Every Java program must contain at least one class.
0 comments