Originally posted by amit taneja:
ok thanx for your reply
but tell me why it can't be non-static method ?
To clarify - it's not that an instance method (non-static method) couldn't instantiate an object of the class - it's that it wouldn't do any good to the outside world if that were the
only place in the class where an object of that type was instantiated.
Say we're talking about a class named YouCantMakeMe, with a private constructor. Think of some code in another class... in order to get to use any of the functionality of the YouCantMakeMe class, it would need an instance of that class. If the constructor is private, only a YouCantMakeMe object can call the constructor - this other class can't simply use "new YouCantMakeMe()". It has to depend on something within the YouCantMakeMe class to do the instantiation.... but now, what methods in the YouCantMakeMe class can be called without a YouCantMakeMe instance? Only static methods (that is, the ones you call by referencing the class, not an object instance of the class).
It's a chicken-and-the-egg problem... I can't get an instance until I call this instance method - but I can't call this instance method until I have an instance...
in static it works fine as u show us...but what if i try to instantiate a object from a non-static method that is in same class ?
That should work fine.... and so long as there is
also a static method that gives access to an instance upon which you can CALL that instance method, you'll be able to use it. So you might have to have:
what is Singleton ?
Singleton is a common design pattern in which you want only one instance of a particular class to exist in your program (the entire JVM). It is also generally globally available, meaning you can get the same (only) instance from just about anywhere in your code, so you can think of it as a global variable. To accomplish it, you do something like the following:
and why u ppl are talking about stack overflow ?
I can only guess that Kalyani was thinking of a constructor which instantiated an object of it's class, causing recursive calls to the constructor method. Something like:
do reply..
Hope that helps.
-- Jon