Either Java is fucking retarded or I'm fucking retarded. Can someone help me figure out which one of these statements is true?
I've got a little issue when creating a new Object.
Inside main method:Rational asd = new Rational(1,2);
Rational qwe = new Rational(15,5);
System.out.println(qwe.converter()+" : "+asd.converter());
Relevant code for class "Rational":private static int zaehler;
private static int nenner;
public Rational(int z, int n){
zaehler = z;
nenner = n;
}
public double converter(){
return (double)zaehler/(double)nenner;
}
I've created 2 Objects, called 2 functions and tried to printf the return value of the functions. What happens, is when I create the SECOND Object (qwe) it OVERWRITES the first one, so that it printfs "3 : 3". Why?
If I'm missing something completely obvious Im going to kill myself. Tried rubber duck for about half an hour but now I've given up.
>>59398219
i believe its because the variables are static
>>59398252
You are my hero. Seems like I'm the one who is retarded.
Though why exactly does this lead to my error?
I just copypastad shit from google because I obviously don't know what I'm doing yet.
try changing private to public
t. guy who dont know what hes talking about
>>59398297
Nah, that would only lead to Main being able to access zaehler and nenner directly, though Im not doing that in code anyways.
>>59398292
because static makes only one instance of a static field exist even if you create two or more instances of the class it will be shared by all instances.
>>59398328
I was about to ask:
"my variables are static, but my object isn't, so why does it matter what happens to the variables AFTER my Object is being created?"
but then I realized that the method accesses the (static) variables directly.
Damn, you helped me a lot. Thanks again.
This should really be a compiler warning (member method result entirely dependent on static variables), but sadly everything Java compilers do is translating your code as directly as possible to bytecode.
See your javac man page for possible -Xlint options; at least with OpenJDK, all possible ones are already enabled.