View RSS Feed

Hibernate

Unusual members, part 2

Rate this Entry
by , 08-12-2011 at 12:22 AM (778 Views)
Just like there is a static, otherwise headless, method, the class initialiser, this is an object initialiser (or just initialiser), that is a non-static and completely headless.

Java Code:
public class MyClass
{
    public static class Subclass extends MyClass
    {
        {
            System.out.println("Subclass Initialiser 1");
        }
        public Subclass()
        {
            System.out.println("Subclass Constructor");
        }
        {
            System.out.println("Subclass Initialiser 2");
        }
    }

    {
        System.out.println("Initialiser 1");
    }
    public MyClass()
    {
        System.out.println("Constructor");
    }
    {
        System.out.println("Initialiser 2");
    }



    public static void main(final String... args)
    {
        new Subclass();
        System.out.println("----");
        new Subclass();
    }

}

So want does this print?

Well, the superclass is always constructed before the subclass, and initialisers called in order of appearance from the top down on object construction.
Additionally initialisers are always called before the constructor, so the code prints:

Initialiser 1
Initialiser 2
Constructor
Subclass Initialiser 1
Subclass Initialiser 2
Subclass Constructor
----
Initialiser 1
Initialiser 2
Constructor
Subclass Initialiser 1
Subclass Initialiser 2
Subclass Constructor

Submit "Unusual members, part 2" to Facebook Submit "Unusual members, part 2" to Digg Submit "Unusual members, part 2" to del.icio.us Submit "Unusual members, part 2" to StumbleUpon Submit "Unusual members, part 2" to Google

Updated 08-12-2011 at 05:45 AM by Hibernate

Tags: None Add / Edit Tags
Categories
Java's syntax

Comments