Java Planet

O Javie i jej otoczeniu

Jak rodzi się obiekt

Tytuł trochę przewrotny, ale będzie o tworzeniu nowego obiektu, a dokładniej o tym w jakiej kolejności inicjowane są poszczególne jego elementy

class SuperClass {

	public SuperClass(){
		System.out.println("Super class Constructor");
	}

}

public class InitBlocks extends SuperClass{

	private int properties = propInit();

	private int propInit() {
		System.out.println("properties init");
		return 1;
	}

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

	static {
		System.out.println("static init block");
	}

	{
		System.out.println("instance init block");
	}

	public static void main(String[] args) {
		System.out.println("start main");
		InitBlocks test = new InitBlocks();
		System.out.println("end main");
	}
	/*
	 * REZULTAT:
			static init block
			start main
			Super class Constructor
			properties init
			instance init block
			constructor
			end main
	 */

}

Jeśli w bloku inicjalizacyjnym “wygenerujemy wyjątek” – wyjątek zostanie zwrócony po opakowaniu w: java.lang.ExceptionInInitializerError

You can follow any responses to this entry through the RSS 2.0 feed. You can leave a response, or trackback from your own site.

COMMENTS

No Comments

There are no comments posted yet. Be the first one!

Leave a Replay