Initialization of Classes ?
From "Thinking in Java":
Quote:
It’s interesting to note that creating a reference to a Class object using ".class" doesn’t automatically initialize the Class object.
When I try this:
Code:
package myPackage1;
class Toy
{
Toy(){};
}
public class ToyTest
{
static void printInfo(Class cc)
{
System.out.println("Class name: " + cc.getName()
+ " is interface? " + cc.isInterface());
}
public static void main(String[] args)
throws ClassNotFoundException, InstantiationException, IllegalAccessException
{
Class k = Toy.class;
printInfo(k);
}
}
I get the output:
Class name: myPackage1.Toy is interface? false
But isn't this class supposed to be not initiated ?
Re: Initialization of Classes ?
I will answer my own question:
Code:
class Toy
{
Toy()
{
System.out.println("Initialized!");
}
static
{
System.out.println("Hello!");
}
}
Code:
Class k = Toy.class;
printInfo(k);
Class m = Class.forName("myPackage1.Toy");
Re: Initialization of Classes ?
My only comment is:
The constructor is not called, when the class is initialized. The output is:
Class name: myPackage1.Toy is interface? false
Hello!
So it seems a constructor is called not when the class is initialized, but when an instance of that class is created.
Initializing a class only calls the statements in the static{} block.
Re: Initialization of Classes ?
I would expect the Class object to be initialized when getName() is called.
Note that loading the class and initializing it are two separate steps.
The purpose of a constructor is to create an instance of the class, so it's no surprise that it doesn't run when the class is loaded or initialized.
More here: Execution
db
Re: Initialization of Classes ?
What if I have an instance variable in my class like int age and in my static block if I have something like this.age = 4;
Then what happens ?
Re: Initialization of Classes ?
Answering my own question:
You can't use "this" in a static block.