user3658679 user3658679 - 1 year ago 46
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.


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();

Output is:


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

Answer Source

Your constructor should not contain void.