java - Object, reference and class. Need help understanding some code -
i kind of understand that:
- a class kind of blueprint objects can created from.
- a object actual instance or object gets created.
- a reference address points said object.
what happens when below code called twice?
car batmobile = new car();
will 2 objects created? if so, happens first object? in detail, happens in terms of class, object , reference?
part 2:
is infinite loop? objects keep getting created since constructor makes object , calls on constructor again? how class, object, reference relation work here?
public class alphabet { alphabet abc; public alphabet() { abc = new alphabet(); } }
car batmobile = new car(); 2 objects created?
if it's called twice yes. because line creates new instance of object. doing twice result in 2 new instances. note, however, if try execute same exact line twice in row compiler error because you'd trying re-declare same variable in same scope.
but otherwise, no, there's 1 object being created on line. car
mentioned twice because declares type variable (batmobile
) , constructor (car()
). languages (c#, javascript, untyped languages, etc. not java) have shorthand first use, since it's inferred second. example:
var batmobile = new car();
is infinite loop?
nope, there's no loop here:
public class alphabet{ alphabet abc; public alphabet(){ abc = new alphabet(); } }
there is, however, stack waiting overflown. in order create alphabet
1 must first create alphabet
. run code , see error. infinite loop execute infinitely (assuming each iteration of loop didn't compound use of finite resource), example:
while (true) { car batmobile = new car(); }
this execute without end. code posted, however, end. error. because each call constructor internally calls constructor. call stack finite resource, exhausted.
Comments
Post a Comment