I'm having trouble calling move.m_north from another function.
It is asking me to make the class move and the function m_north static, but if I do i can't reference y unless I make it static too.
I found that if y is static then any dot object I make will have the same value for y, and I need multiple dots
public class dot {
int y=0; //<-- 3. but if I make this static then it will stay the same for every object
public void step(int direction) {
switch (direction){
case 0:
move.m_north(); //<-- 1. is asking to make move.m_north static
}
}
public class move {
public int m_north() {
if (y > 0) {
y -= 1; //<-- 2. but I need to modify and read non static variables
return -1;
} else return -2;
}
}
}
I am able to call m_north if it is not in the move class but there are many similar functions which I believe need to be split up so I can use same names and it becomes easier to find different functions.
I would much appreciate any assistance.
CodePudding user response:
You can make this work by declaring an instance of the move class. For example (with captialization changed to match Java naming conventions):
public class Dot {
int y=0;
Move move = new Move();
public void step(int direction) {
switch (direction){
case 0:
move.m_north();
}
}
public class Move {
public int m_north() {
if (y > 0) {
y -= 1;
return -1;
} else return -2;
}
}
}
Note that Move with an uppercase M is the class name, and move with a lowercase m is the name of an instance variable in the class Dot.
The reason this is required is that m_north requires an enclosing instance of Dot in order to access its y field. To put it another way, you need to call m_north on a specific dot's move instance. Making the method static doesn't provide an enclosing dot in scope.
