Daniel Hill Daniel Hill - 3 months ago 6
Java Question

Set Instance Variable from Method using Java

As the title explains I am hoping to be able to set an Instance Variable using data produced by a calculation contained within a Method.

I produced an example code to demonstrate what I'm trying to do, as well as a solution I pieced together after scouring the internet. Obviously though, I failed to successfully replicate what others had done.

Thanks in advance for your help.

Sidenote: I have no doubt that this may well be closed as a duplicate, but since I have thusfar failed (after thorough searching) to find anything sufficiently informative to allow me to understand this process.

public class Main {

private int Max;

public int getMax() {
return Max;
}

public static void main(String[] args) {
Main Max = new Main();
{
Max.printMax();
}
}

public void myMethod() {
int Lee = 6;
this.Max = Lee;
}

public void printMax() {
Main max = new Main();
int variable = max.getMax();

System.out.println(variable);
}
}

Answer

I think you have some misunderstandings of how instances of a class work. I recommend you to learn the basics of OOP first.

Anyway, although you didn't tell me what should be the expected result, I guess that you want to print 6. So here's the solution:

private int Max;

public int getMax() {
    return Max;
}

public static void main(String[] args) {
    Main Max = new Main();
    Max.printMax();
}

public void myMethod() {
    int Lee = 6;
    this.Max = Lee;
}

public void printMax() {
    this.myMethod();
    int variable = this.getMax();
    System.out.println(variable);
}

Let me explain what I have changed.

  • In your main method, there is no need for the {} after new Main(), so I deleted them.
  • In printMax, there is no need to create a Main instance again because this already is one.
  • The reason why you failed to print 6 was because the variable max was never changed. Why? Because you just declared a method that changes max, but that method (myMethod) is not called! So I just added a line to call myMethod.
Comments