Reputation: 13
When I try to pass enum variable as argument to the class this way:
MyClass newObjectMyClass = new MyClass(EnumArgument.AAA);
and then I try to set this argument value as new variable or pass it to next class:
public class MyClass {
EnumArgument xarg;
public MyClass(EnumArgument qarg) {
xarg = qarg;
}
EnumArgument new = xarg;
NextClass nextClassObject = new NextClassObject(xarg);
public void move(Canvas can) {
Log.i("info", "xarg = " + xarg + " nextClassObject.doSomething = " + nextClassObject.doSomething + " new = " + new);
nextClassObject.doSomething(can);
}
}
Logcat show me something like that:
I/info:﹕ xarg = AAA nextClassObject.doSomething = null new = null threadid=1: thread exiting with uncaught exception
As you see, logcat shows me my "xarg" value well, but "new" variable as null... "new" should have same value as xarg, I'm right?
(I just write this code to show you what I mean, if there is any error it is just probably my mistake.)
I think there is some logical error. When I put this line:
NextClass nextClassObject = new NextClassObject(xarg);
to my move
method it works well.
Upvotes: 0
Views: 336
Reputation: 34628
In Java, initializers are invoked before constructors.
So when you call new Myclass(EnumArgument.AAA)
, memory is allocated. First, all the fields get default values. So it is as if these instructions were performed:
xarg = null;
new = null; // The name "new" is actually illegal
nextClassObject = null;
That's because the default value for reference variables is null
.
The next stage is to calculate and assign the initializers. You have two initializers:
EnumArgument new = xarg;
NextClass nextClassObject = new NextClassObject(xarg);
So you assign the value of xarg
to new
. But from the previous stage, xarg
is null
, so new
is also null
now. nextClassObject
receives a new, non-null object reference - but the argument to the constructor of NextClassObject
is null
!
Then the constructor is called.
public MyClass(EnumArgument qarg) {
xarg = qarg;
}
So now you put the value of your argument - EnumArgument.AAA
- in xarg
. So the value of xarg
is AAA
, but the value of new
is null
, because it was set up in the previous stage, before the constructor assigned the value to xarg
.
If you want new
to contain the value from the argument, you are not supposed to initialize it with an initializer, but assign a value to it in the constructor:
public MyClass(EnumArgument qarg) {
xarg = qarg;
new = xarg;
}
It would be better if you keep all the field declarations strictly before the constructors and methods. That way you won't be confused about the order of execution.
Upvotes: 1