Object and Class
OOPS (Object-Oriented Programming System) is a programming paradigm that solves problems by organizing code around objects, which represent real-world entities. It uses real-world concepts to model problems and solutions.
Main OOP Concepts:
- Inheritance
- Polymorphism
- Encapsulation
- Abstraction
Class :
A class is declared using the
class
keyword. It acts as a blueprint that defines the structure and behavior (data and methods) of objects. A class can contain:
- Fields (variables)
- Methods
- Constructors
- Blocks (static or instance)
- Nested classes and interfaces
class
ClassName
{ // fields // methods }
Object :
An object is an instance of a class that represents a real-world entity. It has three main characteristics:
- State → represents data or properties of the object.
- Behavior → represents functionality (methods) of the object.
- Identity → represents a unique reference to the object in memory.
1. Using
new
keywordMyClass obj = new MyClass();
2.Using Reflection (
Class.forName()
, getDeclaredConstructor().newInstance()
)MyClass obj = (MyClass) Class.forName("MyClass").getDeclaredConstructor().newInstance();
3.Using clone()
method
MyClass obj2 = (MyClass) obj1.clone();
4. Using Deserialization
(Object is recreated from a saved state).
For more details click 👉here
A class is initialized in Java when:
-
An instance of the class is created using the
new
operator. - A static method of the class is invoked.
- A static field of the class is accessed or assigned (unless it’s a compile-time constant).
- Reflection is used (e.g.,
Class.forName("MyClass")
).
Example :
class MyClass { static { System.out.println("Class is being initialized!"); } MyClass() { System.out.println("Constructor called: Object created"); } static void staticMethod() { System.out.println("Static method called"); } } public class TestInitialization { public static void main(String[] args) throws Exception { // Class initialization by creating object MyClass obj1 = new MyClass(); // Class initialization by calling static method MyClass.staticMethod(); // Class initialization using reflection MyClass obj2 = (MyClass) Class.forName("MyClass").getDeclaredConstructor().newInstance(); } }
Output:
Class is being initialized!
Constructor called: Object created
Static method called
Constructor called: Object created
Explanation:
- The static block executes once when the class is initialized.
- Class is initialized when an object is created, a static method is called, or using reflection.
- Each new object triggers the constructor but does not re-run the static block.