Instance variable and constructor - java

I've asked several questions regarding the subject, but it seems like every time I get an answer, I have more questions.
This question is continuation of my other question: Initialization in polymorphism of variables
Anyways, consider the following example.
class A{ //1
int a = 1; //2
}
i heard this conceptually looks like,
class A { //1
int a = 0; //2
A() { //3
super(); //4
a = 1; //5
}
From what I understand, this is because every time an object is created, instance objects are initialized to its default values.
If I put initialization block say,
System.out.print(i);
right below line 2 for both examples, top will print 1 and bottom will print 0. As far as I know, initialization block is executed before constructor. So is this only conceptual representation of constructors only? Or does the code actually change as such when the default constructor is called? Can someone clarify this for me?
Why does it behave this way? In my other question, it seemed to only cause confusion as to which variable is called. Can't instance variable just be declared a=1 and gets used throughout the class? Shouldn't that make it simpler?

As you said, the equivalence between the two classes in your question is only conceptual.
In fact, if an non-static data field has an initialization value, it is initialized before calling the constructor. The initialization block is copied by the compiler to the beginning of every constructor (after the super line), so it is executed after the initialization of the field and before the constructor code itself.

Your description of how int a = 1 gets converted to a constructor is correct, but it is not the whole story.
If, in addition to a, there are other instance fields with initializers, all of their initializers are collected into a single block that runs as part of constructors
If, in addition to field initialization you have general-purpose initializer blocks, their content gets collected into that same block, along with field initializers.
For example, if you have
class A {
{
System.out.println(a);
}
int a = 1;
{
System.out.println(a);
System.out.println(b);
}
int b = 2;
{
System.out.println(b);
}
public A() {
// Code of A
}
}
then the code block prior to Code of A looks like this:
System.out.println(a);
a = 1;
System.out.println(a);
System.out.println(b);
b = 2;
System.out.println(b);
// Code of A
It should be clear now why zero is printed in the initialization block prior to int a = 1 in the block preceding the initializer: initialization blocks are not treated separately from field initializers, their code gets mixed together in the same order that they appear in the source code.

The difference between your example is the order of operations. In your first example, with the initializer block where you said, the order is:
Assign 1 to a (in the declaration)
Output a (in the initializer block)
...but in your example example, it's
Assign 0 (the default value) to a (effectively in the declaration)
Output a (in the initialization block)
Assign 1 to a (in the constructor)
The key to understanding instance initialization for me is this: Instance initialization code is literally copied into the constructors — all of them, including the default one — by the compiler. It's copied in source code order, and it's before anything in the constructor (including super).
Here's a more complete example. Consider this class:
class Example {
// Instance field with initializer
private int i = 5;
// Instance initialization block
{
System.out.println(this.i);
}
// constructor 1
Example() {
System.out.println(this.i * 2);
}
// constructor 2
Example(int _i) {
this.i = _i;
System.out.println(this.i * 3);
}
}
That's compiled into bytecode exactly as though it were this:
class Example {
// Instance field
private int i;
// constructor 1
Example() {
// begin copied code
this.i = 5;
System.out.println(this.i);
// end copied code
System.out.println(i * 2);
}
// constructor 2
Example(int _i) {
// begin copied code
this.i = 5;
System.out.println(this.i);
// end copied code
this.i = _i;
System.out.println(this.i * 3);
}
}
In both cases above, Oracle's Java 8 outputs the exact same bytecode (as viewed by using javap -c Example after compiling):
Compiled from "Example.java"
class Example {
Example();
Code:
0: aload_0
1: invokespecial #1 // Method java/lang/Object."":()V
4: aload_0
5: iconst_5
6: putfield #2 // Field i:I
9: getstatic #3 // Field java/lang/System.out:Ljava/io/PrintStream;
12: aload_0
13: getfield #2 // Field i:I
16: invokevirtual #4 // Method java/io/PrintStream.println:(I)V
19: getstatic #3 // Field java/lang/System.out:Ljava/io/PrintStream;
22: aload_0
23: getfield #2 // Field i:I
26: iconst_2
27: imul
28: invokevirtual #4 // Method java/io/PrintStream.println:(I)V
31: return
Example(int);
Code:
0: aload_0
1: invokespecial #1 // Method java/lang/Object."":()V
4: aload_0
5: iconst_5
6: putfield #2 // Field i:I
9: getstatic #3 // Field java/lang/System.out:Ljava/io/PrintStream;
12: aload_0
13: getfield #2 // Field i:I
16: invokevirtual #4 // Method java/io/PrintStream.println:(I)V
19: aload_0
20: iload_1
21: putfield #2 // Field i:I
24: getstatic #3 // Field java/lang/System.out:Ljava/io/PrintStream;
27: aload_0
28: getfield #2 // Field i:I
31: iconst_3
32: imul
33: invokevirtual #4 // Method java/io/PrintStream.println:(I)V
36: return
}

Instance variables are immediately available with the default variable if not otherwise set: Objects are set to null and primitive types to 0, false etc.
You have 3 options to set the value of an instance variable in Java:
1) Declare and instantiate immediately
class A {
int i = 1;
}
2) Instantiate it in a instance initializer block
class A {
int a; // it is default value 0 at this point
{ a = 1; } //instance initializer block
}
3) Instantiate it in the constructor
class A{
int a; // it is default value 0 at this point
A() {
a = 1;
}
}
During the instantiation of the A object, Java will
first instantiate the variable a to its default if not done by the user,
then it will go through any instance initializer block in the order they appear, and lastly
it will enter the constructor.

Related

How do I explain this code with the initialization of the final instance field? [duplicate]

The below text is from jls http://docs.oracle.com/javase/specs/jls/se7/html/jls-17.html#jls-17.5.3
Even then, there are a number of complications. If a final field is
initialized to a compile-time constant expression (§15.28) in the
field declaration, changes to the final field may not be observed,
since uses of that final field are replaced at compile time with the
value of the constant expression.
Can anyone please give me better explanation for the above. I couldn't understand the statement "changes to the final field may not be observed". May with the help of example.
I couldn't understand the statement changes to the final field may not be observed
It tells that , if a final variable is declared as compile time constant then any change made in the final variable using reflection API further in program will not be visible to the program during execution.
For example consider the code given below:
import java.lang.reflect.*;
class ChangeFinal
{
private final int x = 20;//compile time constant
public static void change(ChangeFinal cf)
{
try
{
Class clazz = ChangeFinal.class;
Field field = clazz.getDeclaredField("x");
field.setAccessible(true);
field.set(cf , 190);//changed x to 190 for object cf
}
catch (Exception ex)
{
ex.printStackTrace();
}
}
public static void main(String[] args)
{
ChangeFinal cf = new ChangeFinal();
System.out.println(cf.x);//prints 20
change(cf);
System.out.println(cf.x);//prints 20
}
}
The Output of the above code is:
20
20
WHY?
The answer lies in the output provided by javap -c command for public static void main:
public static void main(java.lang.String[]);
Code:
0: new #3; //class ChangeFinal
3: dup
4: invokespecial #11; //Method "<init>":()V
7: astore_1
8: getstatic #12; //Field java/lang/System.out:Ljava/io/PrintStream;
11: aload_1
12: invokevirtual #13; //Method java/lang/Object.getClass:()Ljava/lang/Cla
ss;
15: pop
16: bipush 20
18: invokevirtual #14; //Method java/io/PrintStream.println:(I)V
21: aload_1
22: invokestatic #15; //Method change:(LChangeFinal;)V
25: getstatic #12; //Field java/lang/System.out:Ljava/io/PrintStream;
28: aload_1
29: invokevirtual #13; //Method java/lang/Object.getClass:()Ljava/lang/Cla
ss;
32: pop
33: bipush 20
35: invokevirtual #14; //Method java/io/PrintStream.println:(I)V
38: return
}
At line 16 (before changeFinal method is called)the value of cf.x is hardcoded to 20 . And at line 33 (after changeFinal method is called) the value of cf.x is again hardcoded to 20. Therefore , Although the change in the value of final variable x is done successfully by reflection API during execution, but because of x being a compile time constant it is showing its constant value 20.
It means if in a class you have this:
public class Foo {
public final boolean fooBoolean = true; // true is a constant expression
public final int fooInt = 5; // 5 is a constant expression
}
At compile time any reference to Foo.fooBoolean may be replaced with true, and references to Foo.fooInt may be replaced by 5. If at runtime you later change either of those final fields via reflection, the code referencing it (as it was written) may never see it.
It is quite possible for a Java program to observe a final field having two different values at different times, even without reflection, without recompiling multiple versions of the class, and without anything along those lines. Consider the class below:
class X {
static final int x = getX();
static int getX() {
System.out.println("X.x is now " + X.x);
return 1;
}
public static void main(String[] args) {
System.out.println("X.x is now " + X.x);
}
}
Output:
X.x is now 0
X.x is now 1
This happens because some of the code (the first println) is executed before the field's value is assigned, so that code observes the field's default initial value of 0. The field has a default initial value before it is assigned, even though it is final, because it is not a constant field. The text you quoted from the JLS says this kind of thing cannot happen if the field is declared as a constant.

When to declare objects?

I have been working on some of my AP cs projects and came to the wonder the difference between doing this:
public class CalculateTaxes {
private Scanner in;
public CalculateTaxes(){
in = new Scanner(System.in);
}
}
and this:
public class CalculateTaxes {
private Scanner in = new Scanner(System.in);
public CalculateTaxes(){
}
}
I've seen many examples were they declare an object in one line and instantiate it somewhere else in the code. Why not just declare and instantiate an object in the same line?
Lets test how these classes will be compiled.
public class Test1 {
private Scanner in;
public Test1() {
in = new Scanner(System.in);
}
}
and
public class Test2 {
private Scanner in = new Scanner(System.in);
public Test2() {
}
}
If we use javap -c Test1 we will see
Compiled from "Test1.java"
public class Test1 {
public Test1();
Code:
0: aload_0
1: invokespecial #10 // Method java/lang/Object."<init>":()V
4: aload_0
5: new #12 // class java/util/Scanner
8: dup
9: getstatic #14 // Field java/lang/System.in:Ljava/io/InputStream;
12: invokespecial #19 // Method java/util/Scanner."<init>":(Ljava/io/InputStream;)V
15: putfield #22 // Field in:Ljava/util/Scanner;
18: return
}
and if we use it on Test2 we will get
Compiled from "Test2.java"
public class Test2 {
public Test2();
Code:
0: aload_0
1: invokespecial #10 // Method java/lang/Object."<init>":()V
4: aload_0
5: new #12 // class java/util/Scanner
8: dup
9: getstatic #14 // Field java/lang/System.in:Ljava/io/InputStream;
12: invokespecial #19 // Method java/util/Scanner."<init>":(Ljava/io/InputStream;)V
15: putfield #22 // Field in:Ljava/util/Scanner;
18: return
}
So as you can see the initialization of in field in Test2 class was automatically moved by compiler at start of constructor.
In fact this code will be moved at start of each constructor of that class (right after super() call if any) so only difference is that if you have few constructors you can initialize in field in one place outside constructors instead of doing it in every one of them.
But if lets say you want to initialize field depending on some argument passed in constructor then you have to do it in constructors block.
If you intend to assign an object a value in one scope but need it to be visible in another it can be useful to split up the declaration and the assignment.
Pseudocode:
{
// Outer loop
SomeObject a;
if (condition_one == condition_two)
a = new SomeObject(4);
else
a = new SomeObject(12);
a.doStuff();
}
If a had been declared only inside of the if statements, it wouldn't be visible outside of that loop.
{
if (a == b)
SomeObject a = new SomeObject(5);
a.doStuff(); // ERROR
}
There's not much difference in this case. In some cases, you use different parameters depending on what parameters are sent in the constructor.
Ultimately, in a professional programming environment, your goal is not what is best "right now", but what will help you understand what's going on in 6 months when you need to reread your code and understand WHY you were doing something. HOW you implemented it will help document the intent.

Why do instance variables have default values in java? [duplicate]

This question already has answers here:
Uninitialized class members in Java do not issue any compiler errors. local variables however do. Why?
(5 answers)
Closed 6 years ago.
Why do variables declared in a class have default values, but the variables declared inside methods, said to be "local variables", don't have default values in Java?
For example
class abc
{
int a;
public static void main(String ss[])
{
int b;
abc aa=new abc();
System.out.println(aa.a);
System.out.println(b);
}
}
In this above example variable a has default value of 0 but variable b gives error that it might not have been initialized.
All member variable have to load into heap so they have to initialized with default values when an instance of class is created. In case of local variables, they don't get loaded into heap they are stored in stack until they are being used before java 7, so we need to explicitly initialize them.
Now the "Java Hotspot Server Compiler" performs "escape analysis" and decides to allocate some variables on the stack instead of the heap.
Local variables Initialization
Variables declared in methods and in blocks are called local variables. Local variable are not initialized when they are created at method invocation. Therefore, a local variable must be initialized explicitly before being used. Otherwise the compiler will flag it as error when the containing method or block is executed.
Example:
public class SomeClassName{
public static void main(String args[]){
int total;
System.out.println("The incremented total is " + total + 3); //(1)
}
}
The compiler complains that the local variable total used in println statement at (1) may not be initialized.
Initializing the local variable total before usage solves the problem:
public class SomeClassName{
public static void main(String args[]){
int total = 45; //Local variable initialized with value 45 System.out.println("The incremented total is " + total+ 3); //(1)
}
}
Fields initialization
If no initialization is provided for an instance or static variable, either when declared or in an initializer block, then it is implicitly initialized with the default value of its type.
An instance variable is initialized with the default value of its type each time the class is instantiated, that is for every object created from the class.
A static variable is initialized with the default value of its type when the class is first loaded.
As local variables are allocated on stack, memory chunk for a local variable is allocated when it is assigned with a value.
Take simple example
class Abc {
int i = -111;
int e;
int doSomething() {
int a = 10;
int b = a + i;
int c = b + 100;
Abc d = new Abc();
e = b + c + d.a;
return e + 1000;
}
}
and the bytecode from javap -c Abc
Compiled from "Abc.java"
class Abc {
int i;
int e;
Abc();
Code:
0: aload_0
1: invokespecial #1 // Method java/lang/Object."<init>":()V
4: aload_0
5: bipush -111
7: putfield #2 // Field i:I
10: return
int doSomething();
Code:
0: bipush 10
2: istore_1
3: iload_1
4: aload_0
5: getfield #2 // Field i:I
8: iadd
9: istore_2
10: iload_2
11: bipush 100
13: iadd
14: istore_3
15: new #3 // class Abc
18: dup
19: invokespecial #4 // Method "<init>":()V
22: astore 4
24: aload_0
25: iload_2
26: iload_3
27: iadd
28: aload 4
30: getfield #2 // Field i:I
33: iadd
34: putfield #5 // Field e:I
37: aload_0
38: getfield #5 // Field e:I
41: sipush 1000
44: iadd
45: ireturn
}
When a method is inovked a memory space in the stack called current frame is allocated
If you look carefully even int a=-111; assignment happens in an implicit init function Abc() !
int a = -111;
5: bipush -111
7: putfield #2 // Field a:I
As field variable e is not assigned any value it will be 0 if primitive or null if a Object reference
And if you look at doSomething()
int a = 10;
0: bipush 10
for a local to be used the initial value needs to be pushed into stack in this case 10 . without this 'push' [initialization] a's value is not accessible to subsequent statements (as the value is not on the stack). once the value is pushed to stack other operations like iadd istore etc are carried out on the stack
below statement actually creates an object on the heap space and invokes init method. This is where un initialized variables like 'e' gets default values
15: new #3 // class Abc
18: dup
I leave further bytecode comparison upto you ;) but I hope it is clear
tl;dr: It was more or less an arbitrary choice
If you ask me, it was a mistake that Java has default values for instance variables. The compiler should have forced the programmer to initialize it before like it is the case for local variables.
The rationale behind the default values is safety. When an object is instantiated, a chunk of memory will be allocated for the object which contains where the instance variables are pointing to etc. The Java designers decided it would be a good idea to wipe this part of memory with zeros and nulls. This way you will never read garbage that happened to be there before the object was allocated. They could have forced initialization; there is nothing fundamental about the choice. It probably made things easy to implement and made enough sense to the designers of Java.
In case of local variables, the designers chose to force initialization (or perhaps it's more accurate to say they chose to not do any kind of initialization when a local variable is only declared, and thus the most logical behavior of the compiler was to force initialization of the variable before use).

Java final field compile-time constant expression

The below text is from jls http://docs.oracle.com/javase/specs/jls/se7/html/jls-17.html#jls-17.5.3
Even then, there are a number of complications. If a final field is
initialized to a compile-time constant expression (§15.28) in the
field declaration, changes to the final field may not be observed,
since uses of that final field are replaced at compile time with the
value of the constant expression.
Can anyone please give me better explanation for the above. I couldn't understand the statement "changes to the final field may not be observed". May with the help of example.
I couldn't understand the statement changes to the final field may not be observed
It tells that , if a final variable is declared as compile time constant then any change made in the final variable using reflection API further in program will not be visible to the program during execution.
For example consider the code given below:
import java.lang.reflect.*;
class ChangeFinal
{
private final int x = 20;//compile time constant
public static void change(ChangeFinal cf)
{
try
{
Class clazz = ChangeFinal.class;
Field field = clazz.getDeclaredField("x");
field.setAccessible(true);
field.set(cf , 190);//changed x to 190 for object cf
}
catch (Exception ex)
{
ex.printStackTrace();
}
}
public static void main(String[] args)
{
ChangeFinal cf = new ChangeFinal();
System.out.println(cf.x);//prints 20
change(cf);
System.out.println(cf.x);//prints 20
}
}
The Output of the above code is:
20
20
WHY?
The answer lies in the output provided by javap -c command for public static void main:
public static void main(java.lang.String[]);
Code:
0: new #3; //class ChangeFinal
3: dup
4: invokespecial #11; //Method "<init>":()V
7: astore_1
8: getstatic #12; //Field java/lang/System.out:Ljava/io/PrintStream;
11: aload_1
12: invokevirtual #13; //Method java/lang/Object.getClass:()Ljava/lang/Cla
ss;
15: pop
16: bipush 20
18: invokevirtual #14; //Method java/io/PrintStream.println:(I)V
21: aload_1
22: invokestatic #15; //Method change:(LChangeFinal;)V
25: getstatic #12; //Field java/lang/System.out:Ljava/io/PrintStream;
28: aload_1
29: invokevirtual #13; //Method java/lang/Object.getClass:()Ljava/lang/Cla
ss;
32: pop
33: bipush 20
35: invokevirtual #14; //Method java/io/PrintStream.println:(I)V
38: return
}
At line 16 (before changeFinal method is called)the value of cf.x is hardcoded to 20 . And at line 33 (after changeFinal method is called) the value of cf.x is again hardcoded to 20. Therefore , Although the change in the value of final variable x is done successfully by reflection API during execution, but because of x being a compile time constant it is showing its constant value 20.
It means if in a class you have this:
public class Foo {
public final boolean fooBoolean = true; // true is a constant expression
public final int fooInt = 5; // 5 is a constant expression
}
At compile time any reference to Foo.fooBoolean may be replaced with true, and references to Foo.fooInt may be replaced by 5. If at runtime you later change either of those final fields via reflection, the code referencing it (as it was written) may never see it.
It is quite possible for a Java program to observe a final field having two different values at different times, even without reflection, without recompiling multiple versions of the class, and without anything along those lines. Consider the class below:
class X {
static final int x = getX();
static int getX() {
System.out.println("X.x is now " + X.x);
return 1;
}
public static void main(String[] args) {
System.out.println("X.x is now " + X.x);
}
}
Output:
X.x is now 0
X.x is now 1
This happens because some of the code (the first println) is executed before the field's value is assigned, so that code observes the field's default initial value of 0. The field has a default initial value before it is assigned, even though it is final, because it is not a constant field. The text you quoted from the JLS says this kind of thing cannot happen if the field is declared as a constant.

Issue with constructors of nested class

This question is about interesting behavior of Java: it produces
additional (not default) constructor for nested classes in some
situations.
This question is also about strange anonymous class, which Java
produces with that strange constructor.
Consider the following code:
package a;
import java.lang.reflect.Constructor;
public class TestNested {
class A {
A() {
}
A(int a) {
}
}
public static void main(String[] args) {
Class<A> aClass = A.class;
for (Constructor c : aClass.getDeclaredConstructors()) {
System.out.println(c);
}
}
}
This will prints:
a.TestNested$A(a.TestNested)
a.TestNested$A(a.TestNested,int)
Ok. Next, lets make constructor A(int a) private:
private A(int a) {
}
Run program again. Receive:
a.TestNested$A(a.TestNested)
private a.TestNested$A(a.TestNested,int)
It is also ok. But now, lets modify main() method in such way (addition of new instance of class A creation):
public static void main(String[] args) {
Class<A> aClass = A.class;
for (Constructor c : aClass.getDeclaredConstructors()) {
System.out.println(c);
}
A a = new TestNested().new A(123); // new line of code
}
Then input becomes:
a.TestNested$A(a.TestNested)
private a.TestNested$A(a.TestNested,int)
a.TestNested$A(a.TestNested,int,a.TestNested$1)
What is it: a.TestNested$A(a.TestNested,int,a.TestNested$1) <<<---??
Ok, lets again make constructor A(int a) package local:
A(int a) {
}
Rerun program again (we don't remove line with instance of A creation!), output is as in the first time:
a.TestNested$A(a.TestNested)
a.TestNested$A(a.TestNested,int)
Questions:
1) How this could be explained?
2) What is this third strange constructor?
UPDATE: Investigation shown following.
1) Lets try to call this strange constructor using reflection from other class.
We will not able to do this, because there isn't any way to create instance of that strange TestNested$1 class.
2) Ok. Lets do the trick. Lets add to the class TestNested such static field:
public static Object object = new Object() {
public void print() {
System.out.println("sss");
}
};
Well? Ok, now we could call this third strange constructor from another class:
TestNested tn = new TestNested();
TestNested.A a = (TestNested.A)TestNested.A.class.getDeclaredConstructors()[2].newInstance(tn, 123, TestNested.object);
Sorry, but I absolutely don't understand it.
UPDATE-2: Further questions are:
3) Why Java use special anonymous inner class for an argument type for this third synthetic constructor? Why not just Object type, of constructor with special name?
4) What Java could use already defined anonymous inner class for those purposes? Isn't this some kind of violation of security?
The third constructor is a synthetic constructor generated by the compiler, in order to allow access to the private constructor from the outer class. This is because inner classes (and their enclosing classes' access to their private members) only exist for the Java language and not the JVM, so the compiler has to bridge the gap behind the scenes.
Reflection will tell you if a member is synthetic:
for (Constructor c : aClass.getDeclaredConstructors()) {
System.out.println(c + " " + c.isSynthetic());
}
This prints:
a.TestNested$A(a.TestNested) false
private a.TestNested$A(a.TestNested,int) false
a.TestNested$A(a.TestNested,int,a.TestNested$1) true
See this post for further discussion: Eclipse warning about synthetic accessor for private static nested classes in Java?
EDIT: interestingly, the eclipse compiler does it differently than javac. When using eclipse, it adds an argument of the type of the inner class itself:
a.TestNested$A(a.TestNested) false
private a.TestNested$A(a.TestNested,int) false
a.TestNested$A(a.TestNested,int,a.TestNested$A) true
I tried to trip it up by exposing that constructor ahead of time:
class A {
A() {
}
private A(int a) {
}
A(int a, A another) { }
}
It dealt with this by simply adding another argument to the synthetic constructor:
a.TestNested$A(a.TestNested) false
private a.TestNested$A(a.TestNested,int) false
a.TestNested$A(a.TestNested,int,a.TestNested$A) false
a.TestNested$A(a.TestNested,int,a.TestNested$A,a.TestNested$A) true
First of all, thank you for this interesting question. I was so intrigued that I could not resist taking a look at the bytecode. This is the bytecode of TestNested:
Compiled from "TestNested.java"
public class a.TestNested {
public a.TestNested();
Code:
0: aload_0
1: invokespecial #1 // Method java/lang/Object."<init>":()V
4: return
public static void main(java.lang.String[]);
Code:
0: ldc_w #2 // class a/TestNested$A
3: astore_1
4: aload_1
5: invokevirtual #3 // Method java/lang/Class.getDeclaredConstructors:()[Ljava/lang/reflect/Constructor;
8: astore_2
9: aload_2
10: arraylength
11: istore_3
12: iconst_0
13: istore 4
15: iload 4
17: iload_3
18: if_icmpge 41
21: aload_2
22: iload 4
24: aaload
25: astore 5
27: getstatic #4 // Field java/lang/System.out:Ljava/io/PrintStream;
30: aload 5
32: invokevirtual #5 // Method java/io/PrintStream.println:(Ljava/lang/Object;)V
35: iinc 4, 1
38: goto 15
41: new #2 // class a/TestNested$A
44: dup
45: new #6 // class a/TestNested
48: dup
49: invokespecial #7 // Method "<init>":()V
52: dup
53: invokevirtual #8 // Method java/lang/Object.getClass:()Ljava/lang/Class;
56: pop
57: bipush 123
59: aconst_null
60: invokespecial #9 // Method a/TestNested$A."<init>":(La/TestNested;ILa/TestNested$1;)V
63: astore_2
64: return
}
As you can see, the constructor a.TestNested$A(a.TestNested,int,a.TestNested$1) is invoked from your main method. Furthermore, null is passed as the value of the a.TestNested$1 parameter.
So let's take a look at the mysterious anonymous class a.TestNested$1:
Compiled from "TestNested.java"
class a.TestNested$1 {
}
Strange - I would have expected this class to actually do something. To understand it, let's take a look at the constructors in a.TestNested$A:
class a.TestNested$A {
final a.TestNested this$0;
a.TestNested$A(a.TestNested);
Code:
0: aload_0
1: aload_1
2: putfield #2 // Field this$0:La/TestNested;
5: aload_0
6: invokespecial #3 // Method java/lang/Object."<init>":()V
9: return
private a.TestNested$A(a.TestNested, int);
Code:
0: aload_0
1: aload_1
2: putfield #2 // Field this$0:La/TestNested;
5: aload_0
6: invokespecial #3 // Method java/lang/Object."<init>":()V
9: return
a.TestNested$A(a.TestNested, int, a.TestNested$1);
Code:
0: aload_0
1: aload_1
2: iload_2
3: invokespecial #1 // Method "<init>":(La/TestNested;I)V
6: return
}
Looking at the package-visible constructor a.TestNested$A(a.TestNested, int, a.TestNested$1), we can see that the third argument is ignored.
Now we can explain the constructor and the anonymous inner class. The additional constructor is required in order to circumvent the visibility restriction on the private constructor. This additional constructor simply delegates to the private constructor. However, it cannot have the exact same signature as the private constructor. Because of this, the anonymous inner class is added to provide a unique signature without colliding with other possible overloaded constructors, such as a constructor with signature (int,int) or (int,Object). Since this anonymous inner class is only needed to create a unique signature, it does not need to be instantiated and does not need to have content.

Categories