Classes, objects, instance vs static members, and object initialization.
Question 1: What is a class in Java?
Ans
A class is a blueprint that defines the fields (state) and methods (behavior) that objects created from it will have. The class itself doesn't hold any real data — it just describes the shape and behavior that each object built from it will follow.
Example
java
class Student {
String name;
void study() { System.out.println(name + " is studying"); }
}
Important Point
Declaring a class does not create any object — objects only come into existence when you use new.
Question 2: What is an object in Java?
Ans
An object is a concrete, runtime instance of a class, with its own identity, its own copy of instance fields, and access to the behavior defined by its class. Many separate objects can be created from the same class, each holding different data.
Example
java
Student s1 = new Student();
s1.name = "Rahul";
Student s2 = new Student();
s2.name = "Amit";
Important Point
s1 and s2 are different objects with independent state, even though they were built from the exact same class.
Question 3: What is this keyword?
Ans
this refers to the current object inside an instance context. It is commonly used to distinguish fields from parameters and to call another constructor.
It improves clarity when constructor or method parameters have the same names as fields.
Example
java
class User {
String name;
User(String name) {
this.name = name;
}
}
Important Point
`this()` can call another constructor, and it must be the first statement in that constructor.
Question 4: What is static?
Ans
static declares a member that belongs to the class rather than to each individual object.
Static fields are useful for class-level shared state, and static methods are useful when behavior does not require an object instance.
Example
java
class Counter {
static int count = 0;
Counter() { count++; }
}
Important Point
A static method cannot directly access an instance field because no particular object is implied.
Question 5: What is static block?
Ans
A static initializer block runs when the class is initialized, subject to the JVM's class-initialization rules.
It can initialize complex static state, although normal field initialization is often clearer.
Example
java
class Config {
static int value;
static { value = 100; }
}
Important Point
Static initialization occurs once per class initialization in a given class loader context.
Question 6: What is instance initializer block?
Ans
An instance initializer block runs during object construction as part of initializing an instance, in the order it appears relative to field initializers and constructors.
It is legal but less common than putting initialization directly in constructors or field initializers.