PrashanD
PrashanD

Reputation: 2764

Java: When is the variable "this" initialized?

public class MainMDI extends javax.swing.JFrame {

   private static MainMDI thiz; 

      public MainMDI() {
        initComponents();
        thiz = this;
      }
}  

I'm creating an MDI application in swing. Class MainMDI is the main class of the application and therefore the main method resides in that class. The above code creates a static variable called thiz that points to the instance of class MainMDI when the application runs.

I'm planning to use variable thiz to access non-static (instance) members of class MainMDI from within the main method.(I cannot access non-static members from from within the main method since the main method is a static member in class MainMDI in my application).

public class MainMDI extends javax.swing.JFrame {

   private static MainMDI thiz = this; 

      public MainMDI() {
        initComponents();
      }
}  

But when I attempt to initialize variable thiz as in the above code, compiler says non-static variable this cannot be referenced from a static context. But I'm not referring to this in a static context here am I? Is this because variable this, being non-static, is not yet initialized when the static variable this is initialized?

Also, would it have been a better programming practice if I had not set class MainMDI as the main class and created another class with a main method in it and set that class as the main class?

Upvotes: 0

Views: 299

Answers (2)

Perception
Perception

Reputation: 80623

But when I attempt to initialize variable thiz as in the above code, compiler says non-static variable this cannot be referenced from a static context. But I'm not referring to this in a static context here am I?

Yes, you are. Static class variables are initialized when the class is loaded (not when an object instance is being created). There is no this in that context. The code:

private static javax.swing.JFrame thiz = this; 

Will simply not work. Despite your assertions to the contrary, you do want a singleton. Otherwise, given N possible object instances of your MainMDI object, which one would you be expecting to access from a static context? You should consider refactoring your code rather than trying to strong-arm around Java language semantics.

Upvotes: 5

sharptooth
sharptooth

Reputation: 170509

this means "the object instance currently being operated on", it only makes sense inside a non-static member function. In general this is implicitly passes to each non-static member function when you call that member function so it'd be fair to say that it is initialized right before a non-static member function gets called.

Whether factoring out a class with "main" method is a good idea will heavily depend on actual implementation details.

Upvotes: 3

Related Questions