2

I know there is a question on here somewhere answering this, as I've read it before. I just can't for the life of me find it, nor find it on google.

The question i remember from before was about the order of various methods and pieces of code being called, and there was a particular section which was apparently called the second the class is imported (which can also be used to do nasty unexpected things). What is this called / how would i go about doing it?

If i recall correctly, it was something like this:

Java file 1:

...
import somepackage.myclass; //prints "class imported"
...
myclass a = new myclass(); //print "constructor"
...

Java file 2

package somepackage;

public class myclass {
    ...
    //Something to print out "class imported"
    ...
    public void myclass(){
      System.out.println("constructor");
    }
}

The question / answers had several such constructs like this, but i can't remember what any of them were called. Can someone point me in the right direction please?

will
  • 10,260
  • 6
  • 46
  • 69

2 Answers2

3

Try this:

public class Myclass {
    static {
        System.out.println("test");
    }
}

This is called a Static Initialization Block.

mk.
  • 11,360
  • 6
  • 40
  • 54
  • This is exactly it. Thanks. Are there other constructs like this too? – will Mar 02 '15 at 19:01
  • There's a non-static initialization block, usually used to initialize non-static fields (just delete the static keyword). But nothing else that will be called when the class is [first used](http://stackoverflow.com/q/2007666/154066). – mk. Mar 02 '15 at 19:03
  • Ah i found it, the others are the ones which have no `static` keyword. – will Mar 02 '15 at 19:03
  • It says that isntance initializers are "copied into every constructor". is the copied code placed before, or after what is already there? – will Mar 02 '15 at 19:06
  • Before, but after the (usually implicit) `super()` constructor call. – mk. Mar 02 '15 at 19:08
  • Ah, i didn't know that `super()` was automatically added to the end of the constructor if i didn't call one myself. So java adds a call to `super()` to the beginning of an constructor i create if i don't call it somewhere myself? – will Mar 02 '15 at 19:14
  • So if i have a `super(...)` in there myself, then the instance initializer is jsut copied in before everything. Got it. Cheers. – will Mar 02 '15 at 19:48
  • ...yep, before everything - except the super, though. `super` is always first. But test it out with System.out.println, then you'll be sure. – mk. Mar 02 '15 at 19:57
2

You're probably thinking of a static initializer:

package somepackage;

public class myclass {
    static{
      System.out.println("class imported");
    }

    public void myclass(){
      System.out.println("constructor");
    }
}

The static initializer for a class gets run when the class is first accessed, either to create an instance, or to access a static method or field.

Mshnik
  • 7,032
  • 1
  • 25
  • 38