the key feature of a constructor is that it runs before the object can be assigned to a reference.
Matthew Brown wrote:3. Every time you have the code new Foo(), it creates a new Foo object. Which means that in your final example, it prints the result twice because you're creating two separate objects.
Matthew Brown wrote:1/2. Yes, it's recursion. Specifically, your line Foo f = new Foo(); And the important point is that this is declaring an instance variable of the Foo class.
Which means that whenever you create a Foo, inside that it creates another Foo. Inside that it creates another Foo. And so on.
1) Does the compiler display a StackOverflowError message in the original code because of recursion or is it something else?
2) If it is recursion, how is the code "calling itself"?
3) When I assign the reference variable locally (although, I did not use it) like in solution 2, why does the compiler display the result twice?
1) What exactly is creating the Foo object? Is it the syntax new Foo by itself or Foo f = new Foo.
2) When you say this is declaring an instance variable, I would like to know how is this so because I'm still a little confused about reference variables.
Mihai Boisteanu wrote:
1. It is the sintax new Foo(). When you write Foo f = new Foo() you just create a new object Foo and also reference that object with this f.
2. Instance variables are any variables, without "static" field modifier, that are defined within the class body and outside any class's methods body.
The only way you can access an object is through a reference variable. A reference variable is declared to be of a specific type and that type can never be changed. Reference variables can be declared as static variables, instance variables, method parameters, or local variables.
I suggest you start reading some books or some online documentation until you fully understand this.
Did you see how Paul cut 87% off of his electric heat bill with 82 watts of micro heaters? |