Page 1 of 1
About Question enthuware.ocajp.i.v7.2.1131 :
Posted: Wed Feb 20, 2013 11:00 am
by ETS User
I cannot conceptually get how we can have a static reference to a class of the type that it's being defined in. I get the concept of the question but not how 'static TestClass ref;' works.
Can you explain please?
Thanks
Re: About Question enthuware.ocajp.i.v7.2.1131 :
Posted: Wed Feb 20, 2013 5:33 pm
by admin
In this case, ref is just a static field in class, which happens to be of type TestClass.
I am just guessing that you are confused because at the time of declaring the class, you dont know the size of the class and so having a member of the same time may cause a recursion type scenario.
But ref is just like a pointer. So it doesn't have to know the space needed to store an object of type TestClass because the size of the pointer is constant. So it can point to any object even if that object is of the same type as the declaring class and even if the type of the object that it is pointing to is not known.
HTH
Re: About Question enthuware.ocajp.i.v7.2.1131 :
Posted: Wed Feb 20, 2013 9:41 pm
by Guest
So if you did
static TestClass ref = new TestClass();
would it be an error?
Re: About Question enthuware.ocajp.i.v7.2.1131 :
Posted: Thu Feb 21, 2013 7:38 am
by admin
No, why? As I said, ref is just a pointer. It can point to anything and its size would still be the same.
Re: About Question enthuware.ocajp.i.v7.2.1131 :
Posted: Thu Feb 21, 2013 8:47 am
by admin
As an exercise, try running this code:
Code: Select all
public class RecursiveObject {
public RecursiveObject obj = new RecursiveObject(); //Make it static and try again
int[] ia = new int[1000];
public static void main(String[] args) {
RecursiveObject ro = new RecursiveObject();
}
}
Re: About Question enthuware.ocajp.i.v7.2.1131 :
Posted: Tue Oct 06, 2015 5:45 am
by ncowan
Thanks for the utterly useless explanation of "non sense!", really helped me out.
Re: About Question enthuware.ocajp.i.v7.2.1131 :
Posted: Tue Oct 06, 2015 9:12 am
by admin
Not sure what explanation would one need here. The statement is simply not true. Anyway, it has been updated to make it more clear.
thank you for your feedback!