While skimming through amazing Core Java book earlier on today, I re-discovered the initialization blocks theme, that can be used to setup your class data fields.

There are two common ways to initialize class attributes:

  1. Provide value in declaration, i.e. you set the value as you introduce data field
  2. Set value in constructor
public class Testy {
    private int a = 12; // you set value in declaration
    private int b;
    private int c;

    public Testy()
    {
        this.b = 21;      // you set value in constructor
    }
}

However, there’s actually a third way:

  1. Use initialization block
public class Testy {
    private int a = 12; // you set value in declaration
    private int b;
    private int c;

    public Testy()
    {
        this.b = 21;      // you set value in constructor
    }

    // object initialization block
    // executed every time object of the class is constructed
    {
        this.c = 44;
    }
}

What benefit this structure has over other methods? You can use this to abstract common construction logic (when you have several constructors relying on some common initialization). But, the same effect could be achieved by calling common constructor via this() as the first statement to every constructor requiring prior call to common constructor. Overall, I can hardly think about any use case that initialization block could resolve better than using constructors directly. It might be issue of preference.

However, initialization blocks could still be very useful. When? In situations where constructors do not provide a solution: yes I am talking about static fields. If you need some complex logic initializing your static fields, static initialization block resolves the issue neatly:

public class Testy {
    protected static int x;

    // static initialization block
    static   // Note the word "static" before initialization block curly braces.
    {
        Random generator = new Random();
        Testy.x = generator.nextInt(100);
    }
}

NB:
Initialization blocks are executed before constructors and after fields are initialized to their default values (which are either values provided in field declaration or one of true, 0, null depending on type). Static initialization takes place only once – when class is loade

,

As I got into Java seriously, I decided to give several Design Patterns books I own yet another try – I have skimmed through GoF’s master-piece number of times, but being a PHP programmer in PHP4 age, I just had no incentive to study patterns any deeper, as there clearly was no option to apply them. PHP5 is better wrt OO-tion but still looks like a toy.

Overall, I don’t understand the whole idea of implementing simple and easy-to-learn language, get popular, and then redesign the language to include all the goodies from “real languages like C/C++, Java”. But that’s topic for another post, I guess :)

So, now when I have a little more time to experiment with Java, and as it is as object-oriented as one might dream, I wanted to study patterns in details. I plan to post number of articles later this month, but for now, I wanted to capture one (important if you are planning to use UML and Patterns) simple concept – that’s difference between Aggregation and Composition. As simple as it might seem, there quite a lot of people who don’t understand it.

Read the rest of this entry

,

На Java изменить внешний вид программы (так называемые LaF – Look’n'Feel), до крайнего просто. Достаточно задать имя установленного интерфеса в UIManager.setLookAndFeel():

String laf = "com.sun.java.swing.plaf.nimbus.NimbusLookAndFeel"; // определяем новый LaF
UIManager.setLookAndFeel(laf);  // устанавливаем новый LaF
SwingUtilities.updateComponentTreeUI(this);  // обновляем вн. вид компонентов

Для того чтобы посмотреть какие LaF у вас имеются в наличии, делаем следующее:

UIManager.LookAndFeelInfo[] lafs = UIManager.getInstalledLookAndFeels();
for (UIManager.LookAndFeelInfo info : lafs) {
    System.out.println(info);
}

Вот так вот все просто!