user3658679 user3658679 - 5 months ago 10
Java Question

Java: Member object allocated in constructor destroyed?

I've been having some trouble understanding and finding information on a particular circumstance; if a member object is declared and initialized in a constructor, why is the allocation destroyed when the constructor finishes? It works okay for any other method that does the same thing, so I wondered if someone could clear this up for me.

Example:

public class Main {
Integer i;
public void Main() {
i = new Integer(5);
}
void init() {
i = new Integer(5);
}
public static void main(String[] args) {
Main m = new Main();
System.out.println(m.i);
m.init();
system.out.print(m.i);
}
}


Output is:

null
5


Shouldn't the first output be 5 as well? Thanks in advance.

Answer

Your constructor should not contain void.

Comments