I'm currently studying towards my Java associate certificate and I have the official textbook for study. In the text book is the following example code.
public class Island {
Island i;
public static void main(String[] args) {
Island i2 = new Island();
Island i3 = new Island();
Island i4 = new Island();
i2.i = i3;
i3.i = i4;
i4.i = i2;
I understand here that I have initialised 3 Island objects with reference variables i2, i3 and i4 which each point to their own object. i2 is then redirected to point towards i3 and i3 towards i4 etc. What I don't understand is the need for the "i2.i" dot operator, what exactly is it doing here ? is i2 = i3 not as equally valid ?
If anyone has any good resources on where I can read quite in depth into all of the applications of the dot operator in java that would also be helpful, thanks.
You're using an instance variable of the same type as the class itself (see line
Island i). This means, that the classIslandholds an attributeiof the same typeIsland. Every island has therefore a link to another island. Your assignment ofi2.i = i3;defines the instance variable ofi2to bei3. In other words:i2has a link toi3. You can geti3if you havei2.If you used the assignment
i2 = i3, the value ofi2would be overridden by the reference ofi3. This means thati2is not used anymore and the object behindi3would also be the same object behindi2(same object, 2 different variable names).