Search code examples
javastatic-methodsnon-static

Non-Static method from a static context [Comparing two sets of class instances]


I've read up and understand what the error itself means and generally how to solve it, however I'm not sure how to in the case where I'm creating two different sets of instances from two different classes (comparing if two rectangles collide), and if they do - move one off of the other.

public class NPCManager {

public NPCManager(int amountNPC, int NPCGap) {
    //
    populateNPCS();
}

public void update() {
    for(RectNPC NPC : monsters)
        if(ObstacleManager.NPCCollide(NPC.getRectangle())) { //NPCCollide is the error
            //
        }
}

(Above) This is the class creating the instances of NPCs, it should check each NPC using the method shown below.

public class ObstacleManager {

public ObstacleManager(int playerGap, int obstacleGap, int obstacleHeight, int color, int doorcolor) {

    populateObstacles();
}

public boolean NPCCollide(RectNPC NPC) {
    for(Obstacle ob : obstacles) {
        if(ob.NPCCollide(NPC))
            return true;
    }
    return false;
}

(Above) This is the class creating instances of the obstacles, it should check if the NPC collides by using the below.

public class Obstacle implements GameObject {

public Obstacle(int rectHeight, int color, int doorColor, int startX, int startY, int playerGap) {
    //
}

public boolean NPCCollide(RectNPC NPC) {
    /* Checks if the NPC inputted collides with the rectangles */;
}

(Above) The class for creating the obstacles themselves.

The managers are used so when the game restarts it can restart as expected.


Solution

  • It is hard to figure out what you mean by the code. (The code style violations don't help!)

    However, I think you are asking how to make this work:

    for(RectNPC NPC : monsters)
        if(ObstacleManager.NPCCollide(NPC.getRectangle())) { 
            //NPCCollide is the error
            //
        }
    

    The problem is that NPCCollide (ugh! style violation) is an instance method. That means you have to call it on an instance. But ObstacleManager is a class.

    Solution: create an instance of the ObstacleManager class, and call the instance method on that instance.

    However, your application almost certainly requires that there is one and only one instance of the ObstacleManager.

    Solution (part 2): Read up on the "Singleton" design pattern, and turn your ObstacleManager into a singleton class.

    References: