GMX GMX - 4 months ago 7x
Java Question

Variable value through method in a Java class

This is my Java class:

public class Save extends Application {

public int num1;
public int count;

public Save(int n1){

public int getcount()
return (count);


In my main i do this:

new Save(15);
Integer result = new Save().getcount();

Now the value of result should be 1 ... but instead i get result = 0.....

I know that probably will be a super newbie error but someone can tell me please where i wrong?

Thanks in advice


You're initializing a new instance of Save with the second line that stores result. When you call, this you don't supply a parameter, which then makes the compiler use the default constructor, thus not setting count equal to one. The default constructor doesn't take any parameters and does nothing but instantiate the class.

NOTE: Thanks to @JackDaniels for pointing this out: it should throw an error and shouldn't compile because the parameterized constructor should replace the given constructor. That means instantiating the class without any parameters should have stopped the program from compiling.

Save s = new Save(1);
Integer result = s.getcount();

This uses the same instance and passes an integer, calling the custom constructor and sets count to 1.