Home โ€บ Interview Questions โ€บ How can you execute a function as soon as a class โ€ฆ

How can you execute a function as soon as a class is instantiated?

๐ŸŸข Easy Coding Fresher level
1Times asked
Jul 2026Last seen
Jul 2026First seen

๐Ÿ’ก Model Answer

In Python, you can run code immediately when an object is created by placing it inside the __init__ method, which is the constructor. For example:

class MyClass:

def __init__(self):
    self.initialize()
def initialize(self):
    print("Object created")

obj = MyClass() # prints "Object created"

In Java, you achieve the same by putting the code in the constructor or a static initializer block if you want it to run when the class is first loaded:

public class MyClass {

public MyClass() {
    initialize();
}
private void initialize() {
    System.out.println("Object created");
}

}

MyClass obj = new MyClass(); // prints "Object created"

Both approaches ensure the function runs automatically at instantiation time.

This answer was generated by AI for study purposes. Use it as a starting point โ€” personalize it with your own experience.

๐ŸŽค Get questions like this answered in real-time

Assisting AI listens to your interview, captures questions live, and gives you instant AI-powered answers on a discreet on-screen overlay.

Get Assisting AI โ€” Starts at โ‚น500