Programming C, C++, Java, PHP, Ruby, Turing, VB
Computer Science Canada 
Programming C, C++, Java, PHP, Ruby, Turing, VB  

Username:   Password: 
 RegisterRegister   
 Accesing a variable from different class
Index -> Programming, Java -> Java Help
View previous topic Printable versionDownload TopicSubscribe to this topicPrivate MessagesRefresh page View next topic
Author Message
Chinmay




PostPosted: 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
Sponsor
sponsor
HeavenAgain




PostPosted: 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);
     }
}
Display posts from previous:   
   Index -> Programming, Java -> Java Help
View previous topic Tell A FriendPrintable versionDownload TopicSubscribe to this topicPrivate MessagesRefresh page View next topic

Page 1 of 1  [ 2 Posts ]
Jump to:   


Style:  
Search: