Posted: Thu Jan 03, 2008 2:01 am Post subject: Accesing a variable from different class
Ok so i have two classes in two different files and by the way I am a newbie wannabie programmer.
I want to acces and print the variable from the first class, how would i do it?
code:
package class1;
import directory.*;
public class class1 {
public static void main(String str[]) {
public int x= 100;
}
}
class 2
code:
package class2
import directory.*;
public class class2 {
public static void main(String str[]) {
class1 hey;
System.out.println(hey.x);
}
}
Why wouldnt this work?
Sponsor Sponsor
HeavenAgain
Posted: Thu Jan 03, 2008 2:12 am Post subject: RE:Accesing a variable from different class
uh whats the package all about?
and you have 2 main class, which does not work like that....
and your hey object of the class1 is null i believe, and to make it actually point to class1 you have to do something called "instantiate", by adding assigning new class1(); to it, which then calls to the constructor and make it not null
try something like this....
code:
//first class
public class class1
{
public int x = 100;
}
code:
//second class
public class class2
{
public static void main(String[] args)
{
class1 hey = new class1();
System.out.println(hey.x);
}
}