wood burning stoves 2.0*
The moose likes Beginning Java and the fly likes How can a Class create an instance of itself?? Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login
JavaRanch » Java Forums » Java » Beginning Java
Bookmark "How can a Class create an instance of itself??" Watch "How can a Class create an instance of itself??" New topic
Author

How can a Class create an instance of itself??

james dunster
Greenhorn

Joined: May 03, 2009
Posts: 20
This is code from a book I am using to learn Java. This construction is used several times in the book so far and I have also seen it in uni lecture notes. In this case it creates a class called XCopy and in the middle of the Class it calls an instance of itself. Can anyone explain how this can be? How can a Class create an instance of itself before you have finished writing it? But it works.

class XCopy {

public static void main(String[] args) {

int orig =42;
XCopy x=new XCopy(); // <-----------------<< how is this poss?
int y=x.go(orig);
System.out.println(orig+" "+y);
}
int go(int arg) {

arg= arg*2;
return arg;
}
}
Vijitha Kumara
Bartender

Joined: Mar 24, 2008
Posts: 3832

seen it in uni lecture notes


Please use real words when posting (uni instead University) .

In to your question,
How can a Class create an instance of itself before you have finished writing it?


you may thinking in procedural way? Think in Object oriented way.


SCJP 5 | SCWCD 5
[How to ask questions] [Twitter]
james dunster
Greenhorn

Joined: May 03, 2009
Posts: 20
If you are going to criticise my use of vernacular English then perhaps in your posts you should use punctuation, at least one verb in a sentence and the indefinite article where required.

anyone hv a helpful answer 4 me?
Abhijit Rai
Ranch Hand

Joined: Aug 07, 2008
Posts: 41
Hey James,
Just a couple of points

1. The code is not getting executed as soon as you finish writing the code,(First the .java file is compiled into a .class file and then the.class file is executed ).You first gotta save it with a .java extension (eg XCopy.java).

2.Next compile it .To compile the code ,one way would be using javac Xcopy.java command in DOS(ie Windows).

3.Having got the .class file you can now run it on the java virtual machine one way is would be using java XCopy again in DOS.At this step the execution actually occurs .

Now you should notice that when this step is reached there is a complete Java class (XCopy.class )available to the interpreter to make an object of .Hence an object is being created of a complete Java class .

Now when the JVM encounters " XCopy ref=new XCopy() "it creates an object of this class and assigns it to reference "ref".Think of a class as a professor's Lecture notes,now the Professor wont let you have his originals so you have to get it xeroxed .The copy of the originals can be thought of as the object .Hence you may have any number of copies(objects) of a professors original Lecture notes(Class).


Moreover you should go through the discussions about static members in any good book ,I would recommend :
Head first Java,Thinking in Java HTH


SCJP5 ,SCWCD5
salvin francis
Ranch Hand

Joined: Jan 12, 2009
Posts: 928

james dunster wrote:If you are going to criticise my use of vernacular English then perhaps in your posts you should use punctuation, at least one verb in a sentence and the indefinite article where required.

anyone hv a helpful answer 4 me?


Pal,
He was not critising your use of vernacular english
the point mentioned was
Vijitha Kumara wrote:Please use real words when posting


Please refer to this : http://faq.javaranch.com/java/UseRealWords

No one is here to make fun of you, we are all here to help you.


My Website: [Salvin.in] Cool your mind:[Salvin.in/painting] My Sally:[Salvin.in/sally]
salvin francis
Ranch Hand

Joined: Jan 12, 2009
Posts: 928

Change the perspective,

in Oops, its permissible to even do :





output:



In the above code, the Smallest Child's Display method Executes First !!!
and the Parent's Display executes Last !!
Campbell Ritchie
Sheriff

Joined: Oct 13, 2005
Posts: 38873
    
  23
Shut up both of you. Apologies expected, please.
james dunster
Greenhorn

Joined: May 03, 2009
Posts: 20
But you can't do this:

class testAnyClass {
public static void main(String[] args) {

AnyObj a = new AnyObj();
}
}

class AnyObj {

public AnyObj() {
int k=1;
do{
AnyObj newAnyObj = new AnyObj();
k++;
} while (k<5);
}
}

Not that I want to and intuitively I can see that it wont work because the object can't finish making itself for making itself. I just can't see how it works when the object is inside its own class when created.

You split an infinitive in your message. Is that allowed?
Charles Lyons
Author
Ranch Hand

Joined: Mar 27, 2003
Posts: 836
Vijitha Kumara wrote:Please use real words when posting (uni instead University).

Actually, "uni" is listed in the OED as a "chiefly Australian colloquial term for university", though we've adopted it in the UK too. I therefore consider it a real word.

How can a Class create an instance of itself before you have finished writing it?

I can see how this could be confusing. Remember the difference between the definition of a class (and its methods) and its implementation. This allows the Java compiler to first construct a definition of every class (which lists its class name and package, properties, and method signatures) ahead of compiling the implementations for each of those methods. If it does this for each class, it will then know the complete structure of the entire application. On a second pass, it can compile the implementations of each method and reference the signatures it has stored. This two-step compilation is one way to ensure symbols are resolved correctly (it may not actually be the method used by the Java compiler, but it is a sensible approach).

This can be more confusing, yet also more obvious, in C++. There files are included in one-another, rather than referenced by package names. The C++ compiler tends to do compilation in a linear manner, and code like this can be problematic:Now in this case, MyContainer needs to know about ContainerChild, but ContainerChild also needs to know about MyContainer. Since the file is parsed linearly, the latter isn't a problem. But the former is: ContainerChild is only declared (and here also implemented) after MyContainer. The solution in C++ is to first declare the class, then define it later. Like this:This is an explicit example of how a compiled language can differentiate between declarations (one-line classes), definitions (the class structure, usually in a header file) and implementations (the body of the code, usually in a cpp file).

Campbell Ritchie wrote:Apologies expected, please.

I'm sorry


Charles Lyons (SCJP 1.4, April 2003; SCJP 5, Dec 2006; SCWCD 1.4b, April 2004)
Author of OCEJWCD Study Companion for Oracle Exam 1Z0-899 (ISBN 0955160340 / Amazon Amazon UK )
james dunster
Greenhorn

Joined: May 03, 2009
Posts: 20
Campbell Ritchie wrote:Shut up both of you. Apologies expected, please.


Is this really what it is like in here? I was expecting better. Why are people so anal about one minor infraction of the use-real-words dictum in a beginner's first ever post? I am already a bit discouraged because of difficulty with the subject, I really don't need someone whom I dont' know demanding apologies! Or am I taking this seriously when I shouldn't? So fire me.
james dunster
Greenhorn

Joined: May 03, 2009
Posts: 20
Abhijit Rai wrote:Hey James,
Just a couple of points

1. The code is not getting executed as soon as you finish writing the code,(First the .java file is compiled into a .class file and then the.class file is executed ).You first gotta save it with a .java extension (eg XCopy.java).

2.Next compile it .To compile the code ,one way would be using javac Xcopy.java command in DOS(ie Windows).

3.Having got the .class file you can now run it on the java virtual machine one way is would be using java XCopy again in DOS.At this step the execution actually occurs .

Now you should notice that when this step is reached there is a complete Java class (XCopy.class )available to the interpreter to make an object of .Hence an object is being created of a complete Java class .

Now when the JVM encounters " XCopy ref=new XCopy() "it creates an object of this class and assigns it to reference "ref".Think of a class as a professor's Lecture notes,now the Professor wont let you have his originals so you have to get it xeroxed .The copy of the originals can be thought of as the object .Hence you may have any number of copies(objects) of a professors original Lecture notes(Class).


Moreover you should go through the discussions about static members in any good book ,I would recommend :
Head first Java,Thinking in Java HTH



Thank you. The piece of code is actually from Head First Java. I just read the chapter on Numbers and Statics again and I'm even more confused. As I (mis)understand it main() is a static method which is called without creating an instance of the class in which it sits but, in the code XCopy, main does create an instance of the class in which it sits ! So we have a static method creating an object, not of some other class, but of itself. I have been staring at this thing for hours and get my mind around the concept.
Charles Lyons
Author
Ranch Hand

Joined: Mar 27, 2003
Posts: 836
james dunster wrote:Or am I taking this seriously when I shouldn't?
I would guess so... this is mostly a very friendly place! Though the occasional polite dispute/debate has been known.
james dunster
Greenhorn

Joined: May 03, 2009
Posts: 20
[
How can a Class create an instance of itself before you have finished writing it?

I can see how this could be confusing. Remember the difference between the definition of a class (and its methods) and its implementation. This allows the Java compiler to first construct a definition of every class (which lists its class name and package, properties, and method signatures) ahead of compiling the implementations for each of those methods. If it does this for each class, it will then know the complete structure of the entire application. On a second pass, it can compile the implementations of each method and reference the signatures it has stored. This two-step compilation is one way to ensure symbols are resolved correctly (it may not actually be the method used by the Java compiler, but it is a sensible approach).

So that explains why in Salvin Francis' piece of code you can see the value of n go from 20 to 5 before the new objects are made and then from 5 to 20 after/ Not quite sure why it delivers them in opposite order from how they were made; I could ask him.
Vijitha Kumara
Bartender

Joined: Mar 24, 2008
Posts: 3832

Charles Lyons wrote:
Vijitha Kumara wrote:Please use real words when posting (uni instead University).

Actually, "uni" is listed in the OED as a "chiefly Australian colloquial term for university", though we've adopted it in the UK too. I therefore consider it a real word.


Thanks Charles Lyons, for pointing that.

@james dunster

I think my intention was pointed out by salvin francis earlier. Anyway don't get discouraged. Everyone here are nice people trying to help others.
Charles Lyons
Author
Ranch Hand

Joined: Mar 27, 2003
Posts: 836
james dunster wrote:So that explains why in Salvin Francis' piece of code you can see the value of n go from 20 to 5 before the new objects are made and then from 5 to 20 after/ Not quite sure why it delivers them in opposite order from how they were made.
That is basically an example of recursion where the recursive function is the constructor for the object. Recursion is fundamentally a procedural concept, but the key here (which makes this OOP rather than procedural) is that the recursion happens inside the constructor and before the display() method is invoked on each object.

So we start with a constructor A(20), this then creates a new A(19), which creates a new A(18) etc. until we get to A(5) which then calls display() and prints 5, returns from that constructor so the A(6) constructor completes its execution with a display() and prints 6, returns from that constructor back into the A(7) constructor which completes and display() prints 7 etc. all the way back to the original A(20) constructor which does its display() and prints 20. Execution then returns to the main() method which completes and terminates the program.

This has nothing to do with how the compiler does its compilation, and nothing to do with definitions or implementations. It is just recursion of the same function (here a constructor) with a little OOP thrown in. If we weren't doing OOP, you could easily have done the same with:
Vijitha Kumara
Bartender

Joined: Mar 24, 2008
Posts: 3832

So that explains why in Salvin Francis' piece of code you can see the value of n go from 20 to 5 before the new objects are made and then from 5 to 20 after/ Not quite sure why it delivers them in opposite order from how they were made;


Well, those calls inside the constructor A(int n) won't returned until the condition evaluates to false for the first time(i.e: n==5). At that time the last one (one with the value 5 for n) completes it's constructor and returns, so does the rest.
fred rosenberger
lowercase baba
Bartender

Joined: Oct 02, 2003
Posts: 11314
    
  16

Please, everyone, take a deep breath, and calm down. Believe it or not, we're all trying to help here.

the reason we ask everyone to 'use real words' is that we have a large international community. For a lot of folks, English is not their first language, and using colloquialisms like 'uni' instead of 'university' does not make it easy for them to follow. Heck, for a few years after I started spending time here, I didn't know what 'uni' meant - unicycle? universe? unit?

So, the request to use the full spelling of the word is to make it easier for someone reading your post to help YOU. If someone reads a post, would you rather they spend time helping you find the answer, or spend time trying to figure out what your abbreviations mean?

Almost everyone who comes here posts from a full keyboard. Saving 7 keystrokes in a post several hundred long seems rather silly, don't you think?


There are only two hard things in computer science: cache invalidation, naming things, and off-by-one errors
james dunster
Greenhorn

Joined: May 03, 2009
Posts: 20
Charles Lyons wrote:
james dunster wrote:So that explains why in Salvin Francis' piece of code you can see the value of n go from 20 to 5 before the new objects are made and then from 5 to 20 after/ Not quite sure why it delivers them in opposite order ~snip

I understood all of that and now also Silvan Francis' post for which thanks. To those of you still bleating on about the use of the word uni ............wel nvm.



Campbell Ritchie
Sheriff

Joined: Oct 13, 2005
Posts: 38873
    
  23
Charles Lyons wrote: I'm sorry
It wasn't you I meant. You didn't do anything wrong.

I think Fred has said all that is required, while I was away from the keyboard.
salvin francis
Ranch Hand

Joined: Jan 12, 2009
Posts: 928

Silvan


Actually i wanted to demonstrate that the code approach is not linear.


Deviating from main topic:

Most simplest explaination:
Every statement in A is executed.
so when the statement says create an object of A .......
program execution kinda halts there (not really - just for explaination) and the child Object is created (and its constructor is invoked).
This happens recursively until the condition is false. (Always have a terminating condition for recursive calls!!)


Now back to the main topic:
A class can create an instance of itself, rather in real world an anology is that a virus can replicate or an animal can give birth to an offspring

As for the location in code confusion:
A class is defined within a set of curly braces, so everything related to it would occur in that.
Hence the code to create another instance would occur within the class:
In your example: in a static method
In mine : in the constructor.

 
It is sorta covered in the JavaRanch Style Guide.
 
subject: How can a Class create an instance of itself??