Howdy, Stranger!

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

Categories

Welcome to the new platform of Programmer's Heaven! We apologize for the inconvenience caused, if you visited us from a broken link of the previous version. The main reason to move to a new platform is to provide more effective and collaborative experience to you all. Please feel free to experience the new platform and use its exciting features. Contact us for any issue that you need to get clarified. We are more than happy to help you.

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.