I’m sure there is an extremely simple solution for this but I’m desperately struggling to find the answer. I’m trying to set the value from a main class into classA then retrieve that value in classB and do something else with it before returning the answer in the Main:
Example:
public class Main {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
ClassA classA = new ClassA();
ClassB classB = new ClassB();
System.out.println("Number: ");
classA.setX(input.nextInt());
System.out.println("Total: " + classB.printTotal());
} // main
} // class
Class A:
public class ClassA {
int x;
public int getX() {
return x;
}
public void setX(int x) {
this.x = x;
}
} // class
ClassB:
public class ClassB {
ClassA classA;
public int printTotal() {
int y = classA.getX() * 5;
return y;
}
} // class
Whatever I input returns null. I understand why this is the case but I don’t know the solution.
Your
ClassBshould define the dependency onClassAeither through constructor or a (setter) method:And inject the dependency in
mainas follows: