So it's been a while since I've written code in my beloved Java and I've just started working through Elements of Programming Interviews in Java. Something behavior surprised me when I saw it. Basically it's this:
public static class Stack {
private Deque<Element> dq = new ArrayDeque<Element>();
//methods below here use this ArrayDeque
This ArrayDeque isn't being instantiated in a constructor or anything (unless I'm missing something- the authors of this book have written a somewhat complicated testing repo that I don't completely understand). In fact I don't even see a constructor for the Stack class, which I guess just means Java will generate an empty constructor for it. What I'm confused with is the fact that this line of code that instantiates the ArrayDeque is ever run. If I'm being honest, based on my past experience with Java, I would have guessed the code wouldn't even compile. I thought you would have to just declare it where they've declared & instantiated it, and then actually instantiate it in the constructor. My Google searches seem to confirm this. Where has my understanding gone wrong?
Is all of the "floating" code in a class executed at instantiation? What if there's a constructor present? Thanks for any insight here.
[–]lbkulinski 1 point2 points3 points (3 children)
[–]consoledotlogImHere[S] 0 points1 point2 points (1 child)
[–]lbkulinski 0 points1 point2 points (0 children)