How can you create an object within its own class definition? - Programmers Heaven

Howdy, Stranger!

It looks like you're new here. If you want to get involved, click one of these buttons!

Categories

How can you create an object within its own class definition?

mystifiedmystified Posts: 1Member
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;
}
}

Sign In or Register to comment.