Question:
In Java, how to i get a variable from one class to another?
anonymous
2010-11-14 04:34:59 UTC
say, i have class mainclass, in which i have my main function.
then i have another class called secondclass, in which i define 'int theNumber = 5'
how can i use theNumber from secondclass inside mainclass?

i tried to create a method which returns theNumber, i tried something like this:
secondclass scObject = new secondclass();
System.out.println(scObject.theNumber);

i need help, please.
Four answers:
AnalProgrammer
2010-11-14 04:40:34 UTC
Try a getter method

System.out.println (scObject.getTheNumber());



Have fun.
anonymous
2010-11-14 04:50:22 UTC
In the second Class theNumber will have to declared as a member like this:



public secondclass

{

    private int theNumber;



    public secondclass()

    {

        theNumber = 5;

    }



    //then add a get method like this:

    public int getNumber()

    {

        return theNumber;

    }

}



And then in the first Class when you are getting it you just call the method e.g:



public void someMethod()

{

    secondclass scObject = new secondclass();

    System.out.println( scObject.getNumber() );

}



If that helps.



EDIT: You can also set the member to public then youc an access it the way yu first tried but in Java you should avoid suing public members as much as possible. Always create get and set methods for accessing and changing members from other classes.
?
2010-11-14 04:47:32 UTC
Hey, Richard.



The magic of the "get" method isn't that its name contains the word "get." It doesn't matter what it's called, as long as it's declared as public and returns a value of the proper type.



In secondclass, define the method:



public int getTheNumber()

{

return theNumber;

}



... either that, or you can declare the variable itself as public. Within secondclass, define:



public int theNumber = 5;



... then, your scObject.theNumber argument should evaluate correctly.
rudicil
2016-12-17 00:30:58 UTC
the two make the variable public public: element pupil or use a function. public function pupil() { return this.pupil; } * or something like that The latter returns a replica of pupil, so an exterior software can not regulate "pupil" and wreck something.


This content was originally posted on Y! Answers, a Q&A website that shut down in 2021.
Loading...