How do I get some variable from another class in Java? [closed] - java

Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
Questions asking for code must demonstrate a minimal understanding of the problem being solved. Include attempted solutions, why they didn't work, and the expected results. See also: Stack Overflow question checklist
Closed 9 years ago.
Improve this question
I am "playing around" with Java, watching tutorials and trying to get the hang of it. For this question, I'm trying to figure out how I can take a variable from another class and use it in my main one, without making the initial variable public. Here is the code:
I am trying to get int x equal to 5 (as seen in the setNum() method), but when it prints it gives me 0.
Main Class:
package getVarTest;
public class Main {
public static void main (String[]args){
Vars varsObject = new Vars();
int x = varsObject.getNum();
System.out.println(x);
}
}
Variable Class:
package getVarTest;
public class Vars {
private int num;
public void setNum(int x){
this.num = 5;
}
public int getNum(){
return num;
}
}
So, as you can see I am trying to take the private int num and make the int x in the main class equal to it.

I am trying to get int x equal to 5 (as seen in the setNum() method) but when it prints it gives me 0.
To run the code in setNum you have to call it. If you don't call it, the default value is 0.

You never call varsObject.setNum();

Do NOT do that! setNum(num);//fix- until someone fixes your setter. Your getter should not call your setter with the uninitialized value ofnum(e.g.0`).
I suggest making a few small changes -
public static class Vars {
private int num = 5; // Default to 5.
public void setNum(int x) {
this.num = x; // actually "set" the value.
}
public int getNum() {
return num;
}
}

If the variable is public you can get it just by saying packageName.ClassName.variableName, but if it is private you will have to make a getter method inside the class that the variable is in. It will look something like this:
public int getVariableName() {
return variableName;
}
Then just call that method wherever you need it.

Your example is perfect: the field is private and it has a getter. This is the normal way to access a field.
If you need a direct access to an object field, use reflection. Using reflection to get a field's value is a hack and should be used in extreme cases such as using a library whose code you cannot change.

The code that you have is correct. To get a variable from another class you need to create an instance of the class if the variable is not static, and just call the explicit method to get access to that variable. If you put get and set method like the above is the same of declaring that variable public.
Put the method setNum private and inside the getNum assign the value that you want, you will have "get" access to the variable in that case

Related

When Should You Use Get Methods vs Call Variables Directly? [duplicate]

This question already has answers here:
Why use getters and setters/accessors?
(37 answers)
Closed 4 years ago.
ok so i just found out that if you have a class with global variables you can call it in another class just by saying class.variable and now i'm very confused as to why getVariable and setVariable methods exist ever when they're already accessible
so let's say we have these two classes
public class MyClass {
public int num;
public String str;
public MyClass (int num, String str) {
this.num = num;
this.str = str;
}
public int getNum () {
return num;
}
public String getStr () {
return str;
}
}
public class test {
public static void main (String[] args) {
MyClass x = new MyClass (3, "string");
System.out.println(x.num);
System.out.println(x.str);
System.out.println(x.getNum());
System.out.println(x.getStr());
x.num = 4;
System.out.println(x.num);
}
}
Both ways, it accesses the same data from the object and outputs the same thing. Is one way better practice than the other or are there certain cases where one of the ways won't work?
Short answer: encapsulation.
A major benefit is to prevent other classes or modules, especially ones you don't write, from abusing the fields of the class you created.
Say for example you can an instance variable int which gets used as the denominator in one of your class methods. You know when you write your code to never assign this variable a value of 0, and you might even do some checking in the constructor. The problem is that some else might instantiate your class and later assign the instance variable a value of 0, thereby throwing an exception when they later invoke the method that uses this variable as a denominator (you cannot divide by 0).
Using a setter, you write code that guarantees the value of this variable will never be 0.
Another advantage is if you want to make instance variables read only after instantiating the class then you can make the variables private and define only getter methods and no setters.

Why Does (a) print (0)?

i am trying to grasp the idea of ObjectOriented programing can someone explain why the local variable (a) prints zero instead of the set int that is placed in the getter and setter.
These are the objects in the AppClass
Symptoms obj = new Symptoms();
test obj2 = new test();
actionPerformed... i think this is all you need from the AppClass
#Override
public void actionPerformed(ActionEvent e) {
int x = Integer.parseInt((field.getText()));
obj.setSleep(x);
writeSleep();
frame.setVisible(false);
obj2.tester();
readSleep();
initialize2();
}
This is the Symptoms class that i hope to add more symptoms if i can get this to work
public class Symptoms {
private int sleep;
public int getSleep() {
return sleep;
}
public void setSleep(int sleep) {
this.sleep = sleep;
}
}
this is the tester class where i hope to print out the value of (a)
public class test {
public void tester(){
Symptoms get = new Symptoms();
int a;
a = get.getSleep();
System.out.println(a);
}
}
It seems as tho the test class isnt getting the "message" but if i run the same code in the AppClass, given i modify the code a little bit, then (a) will print.
Because the JLS says so, see chapter 4.12.5. Initial Values of Variables:
Each class variable, instance variable, or array component is initialized with a default value when it is created (§15.9, §15.10):
For type int, the default value is zero, that is, 0.
Now after you saw it's confusing, I recommend you to explicitly set it to zero in the future, it's clearer.
In test.tester(), an instance of Symptoms is created and the method setSleep() is never called with it, so getSleep returns the default value of a, which is 0.
You only ever call setSleep in obj.setSleep(x);, where obj is an entirely different instance from get. But since x is not static, calling obj.setSleep doesn't change the value of get.x -- only the value of obj.x.
here is a better version of the question and the answer. It has nothing to do with setting int to zero.
How to set and get with three Classes?

error: cannot assign a value to final variable (int)

Ok I'm sure this is simple, but I'm having issues and my mind is blank. =(
I know 'final' makes it so the variable can't change but that's pretty much all I can figure out about it right now.
And the code...
If I take out the 'final' the error comes up as "error: missing return statement
}" for the first two methods.
EDIT: Thank you all for the help, surprising how fast I got help!
So I just took out 'final' and added 'void' to the first two methods. I'm sure it'll take some time to fully understand everything, but it definitely helps.
There is a part two and here is the part that I have no clue on what to do...
The second part you just have to test this first program. Am I supposed to make a separate file with the same code?
If anyone can help great, but if not thats fine I'll work on it later.
You declare your function as
public static int removeOneFromRoom (int number)
{
totalNumber = totalNumber-number;
}
The emphasis here is the public static int, telling the compiler that your function is supposed to return an integer. You do however not return anything in that function body, so the compiler complains rightfully. Either return something, or declare the return value as void.
Maybe you're missing the return statement for the first two methods. Or you may want to change the return type to void if you don't need to return anything.
Doing these will remove your error but it might differ from what you need.
public static void addOneToRoom(int number)
{
numberInRoom = numberInRoom+number;
}
public static void removeOneFromRoom (int number)
{
totalNumber = totalNumber-number;
}
Hope this helps.
A variable declared with static and final keywords behaves like a constant. But what does that mean ?
It means you can't change their values. In simpler terms if variable is a primitive then you can't change its value but if its a reference variable then you can't change the reference to some other address.
So in your code, declaring numberInRoom and totalNumber variables as static and final is wrong
public static int numberInRoom=3;
public static int totalNumber=30;
public static int addOneToRoom(int number)
{
numberInRoom = numberInRoom+number;
}
public static int removeOneFromRoom (int number)
{
totalNumber = totalNumber-number;
}
Are you sure that you want these variables to be declared as static because such variables shall be shared by all instances of the concerned class. Please have a look at what does declaring variables as static and final means

How can i call a variable from another method

I need to know how to call a variable from one method to another
Can anyone help me?
public static void number(){
number = 1;
}
public static void callNumber(){
/*How can I call number to this method???
*/
}
Actually, "call a variable from an other method" is not very explicit, since a variable in a method is either global (used in the method but naturally available in the entire program), or a local variable of the method.
And in this last situation it is impossible to get this value.
Then either you declare your variable externally and it is trivial, or you specifiy a type value to your method "number()":
public static int number() {
int number = ...;
return number;
}
and you call it:
public static void callNumber() {
int numberReturned = number();
// other things...
}
Note: your code number = 1; specifies that your variable is global...
The trick is to set "number" available either by the return of the method, or by specifying this variable global.
I don't know if I've answered your question, if not try to be more explicit.
Between static methods, variables can be shared by making them global,
or by sending them as parameters(noas described by #Gaétan Séchaud).
However, if those two methods has a continuos connection between them, and they handle some variables needed to be shared, it smells like a class is needed.

How do I pass variables between methods in java? [closed]

Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
Questions asking for code must demonstrate a minimal understanding of the problem being solved. Include attempted solutions, why they didn't work, and the expected results. See also: Stack Overflow question checklist
Closed 9 years ago.
Improve this question
In the main method of my program I have a bunch of scanner input which I have passed into various methods using parameters.
In those various methods I have done calculations, creating new variables.
In my final method I need to add those new variables together, but the compiler will not recognize the new variables because they only exist in those other methods. How would I go about passing the new variables to my final method?
Instead of creating local variables create class variables.The scope of class variables is that they are global meaning you can access those variables anywhere in the class
Variables created in methods are local to methods and scope is restricted to methods only.
So go for instance members, which you can share among methods.
If you declare so, you don't need to pass them among methods, but you can access and update those members in methods.
Consider,
public static void main(String[] args) {
String i = "A";
anotherMethod();
}
You get a compiler error in the below method if you try to access i, because i is a local variable of the main method. You cannot access in other methods.
public static void anotherMethod() {
System.out.println(" " + i);
}
What you can do is, pass that variable to where you want.
public static void main(String[] args) {
String i = "A";
anotherMethod(i);
}
public static void anotherMethod(String param){
System.out.println(" " + param);
}
You can create a List and pass it to each method as parameter. At the end all you need is to iterate through the list and handle the results.
Create an object with new variables and the method returning their sum.
In your methods use this object for new variables calculation.
Then use the object method for getting sum of new variables
You could do something like this:
public void doStuff()
{
//Put the calculated result from the function in this variable
Integer calculatedStuff = calculateStuff();
//Do stuff...
}
public Integer calculateStuff()
{
//Define a variable to return
Integer result;
//Do calculate stuff...
result = (4+4) / 2;
//Return the result to the caller
return result;
}
You also could do this(You can then retrieve the variable calculatedStuff in any function in the class):
public class blabla {
private Integer calculatedStuff;
public void calculateStuff()
{
//Define a variable to return
Integer result;
//Do calculate stuff...
result = (4+4) / 2;
//Return the result to the caller
this.calculatedStuff = result;
}
}
But as everyone else suggest, I also higly recommend to do a basic Java tutorial.

Categories