Home Javatutorials Initialising Fields before Superconstructor call - Java Tutorials



Initialising Fields before Superconstructor call - Java Tutorials
Posted on: April 18, 2011 at 12:00 AM
This page discusses - Initialising Fields before Superconstructor call - Java Tutorials

Initialising Fields before Superconstructor call

2004-03-20 The Java Specialists' Newsletter [Issue 086b] - Initialising Fields before Superconstructor call (Follow-up)

Author: Dr. Heinz M. Kabutz

If you are reading this, and have not subscribed, please consider doing it now by going to our subscribe page. You can subscribe either via email or RSS.

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

This material from The Java(tm) Specialists' Newsletter by Maximum Solutions (South Africa). Please contact Maximum Solutions for more information.

Related Tags for Initialising Fields before Superconstructor call - Java Tutorials:


More Tutorials from this section

Ask Questions?    Discuss: Initialising Fields before Superconstructor call - Java Tutorials  

Post your Comment


Your Name (*) :
Your Email :
Subject (*):
Your Comment (*):
  Reload Image
 
 

Ask Questions?

If you are facing any programming issue, such as compilation errors or not able to find the code you are looking for.

Ask your questions, our development team will try to give answers to your questions.