Nousheed Mohammed

Greenhorn
+ Follow
since Mar 30, 2007
Merit badge: grant badges
For More
Cows and Likes
Cows
Total received
0
In last 30 days
0
Total given
0
Likes
Total received
0
Received in last 30 days
0
Total given
0
Given in last 30 days
0
Forums and Threads
Scavenger Hunt
expand Ranch Hand Scavenger Hunt
expand Greenhorn Scavenger Hunt

Recent posts by Nousheed Mohammed

Will constructors be inherited in the sub class?
Ans is G:

System.out.println(x + y + foo());
first id adds x and y.after that it concats the string.
if you declare x as an instance variable you cant use that x in a static mehod directly... to access that you have to create an instance of the class and on that instance only you can access the variable...

Originally posted by muskaan gaffor:
int x=0; //line#1
public static void main(String d[]) { //line#2
while(x<=0) { // line#3

when i use the above code in my program, it will throw a error, cannot make a static reference to nonstatic fiel x.
---------------------

public static void main(String d[]) { //line#4
int x=5; //line#5
while(x<=0) { // line#6

this compiles fine.

the variables (non static) used in static method.why is not giving error?

regards,
Mussy

Yes, Using == operator we can compare instances of the same class.

Originally posted by Henry Wong:


From the way you wrote the getInstance() method, can't someone just call your method more than once? And get more than once instance of the class?

Henry


The object will be created once in static method and if someone calls this static method more than once, object reference will be returned... it is called singleton class

Originally posted by Thiru Mu:
How can I write a class, so that only one object can be created for the class?


You write a constructor which has private access modifier and create an instance in a static method and return the object reference.
class A
{
private A()
{}
static A getInstance()
{
A a = new A();
return a;
}
}
this way only one object will be created for class A.