Running on Java 24-ea+24-2960 (Preview)
Home of The JavaSpecialists' Newsletter

086bInitialising Fields Before Superconstructor Call (Follow-Up)

Author: Dr. Heinz M. KabutzDate: 2004-03-20Java Version: 1.4Category: Tips and Tricks
 

Abstract: Follow-up to show another approach that works even better for initializing fields prior to the call to super().

 

Gidado-Yisa Immanuel sent me another approach that is a bit simpler to write, hence should reduce the possibility of bugs. Instead of using a static field, and worrying about concurrent access, why not rather just use a ThreadLocal? I must admit that I have never used ThreadLocals because of the problems in previous versions of Java, so that was an option I did not consider.

import javax.swing.*;

public class CustomerView4 extends FormView1 {
  private static final ThreadLocal tempType = new ThreadLocal();
  private Integer type;
  public CustomerView4(JFrame owner, int type) {
    super(hackToPieces(owner, type));
  }
  private static JFrame hackToPieces(JFrame owner, int type) {
    tempType.set(new Integer(type));
    return owner;
  }
  private void init() {
    type = (Integer) tempType.get();
  }
  public JComponent makeUI() {
    init();
    switch (type.intValue()) {
      case 0:
        return new JTextArea();
      case 1:
        return new JTextField();
      default:
        return new JComboBox();
    }
  }
  public static void main(String[] args) {
    CustomerView4 view = new CustomerView4(null, 1);
    System.out.println(view.getMainUIComponent().getClass());
  }
}

This certainly looks simpler than my approach, so rather use Gidado's solution than mine, even though mine is marginally faster (about 1%). And even better than Gidado's solution would be to change the framework :-)

Kind regards from

Heinz

 

Comments

We are always happy to receive comments from our readers. Feel free to send me a comment via email or discuss the newsletter in our JavaSpecialists Slack Channel (Get an invite here)

When you load these comments, you'll be connected to Disqus. Privacy Statement.

Related Articles

Browse the Newsletter Archive

About the Author

Heinz Kabutz Java Conference Speaker

Java Champion, author of the Javaspecialists Newsletter, conference speaking regular... About Heinz

Superpack '23

Superpack '23 Our entire Java Specialists Training in one huge bundle more...

Free Java Book

Dynamic Proxies in Java Book
Java Training

We deliver relevant courses, by top Java developers to produce more resourceful and efficient programmers within their organisations.

Java Consulting

We can help make your Java application run faster and trouble-shoot concurrency and performance bugs...