Win a copy of Design for the Mind this week in the Design forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

class variables

 
mansoor iqbal
Ranch Hand
Posts: 91
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator

class Op_initial {
public int z;
public int x=1;
public static void main (String ar[]) {
int y;
System.out.print("Member z, x=1 "+" "+z+x);
}
}

i get a compile error on the s.o.p line....why?
 
Hari Gangadharan
Ranch Hand
Posts: 73
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
main() is a static method and hence it cannot access non-static properties. Hence the System.out.print will fail on compile. To avoid compile error, you have to declare the properties as static and you should initialize them. Remember that the properties or Class need not be instantiated when we run a static method.

------------------
Hari Gangadharan
Out of the turbulance a soft voice spoke to me ...
Son smile and be happy things could be worse...
I smiled and I was happy and things became worse!
 
mansoor iqbal
Ranch Hand
Posts: 91
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
but how shd i access the variables declared in the code without declaring them static?
that is the question
 
Ajith Kallambella
Sheriff
Posts: 5782
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Create an instance of class and use the object to access instance variables.!!
 
Fawad Khan
Ranch Hand
Posts: 36
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Mansoor Sb,
Eid Mubarak, for this problem u should use
Op_initial OI = new Op_initial();
and then
(OI.z+OI.x)
I am sure that it will work this way.
 
mansoor iqbal
Ranch Hand
Posts: 91
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
thank u fawad. eid mubarak to u as well..thanks for ur sms..and i hope u got me email...
this just means that the class variables cant be directly accessed ... unless they r static.
 
Hari Gangadharan
Ranch Hand
Posts: 73
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
The basic principle is that you cannot use a non-static method or variable until the Class is instantiated. Since the Class will not instantiated when we execute the class using java, main should be declared as static. Now since main is static, main or any static methods can only call static methods and can only access static properties. This is because, the other properties need not be available when we run a static methods.
Hope it clears your doubts --

------------------
Hari Gangadharan
Out of the turbulance a soft voice spoke to me ...
Son smile and be happy things could be worse...
I smiled and I was happy and things became worse!
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic