Note that there are some explanatory texts on larger screens.

plurals
  1. POCalling a method from outside a class in Java
    primarykey
    data
    text
    <p>This seems to be a common question on here but for all the ones I read, they seem to deal with different things.</p> <p>I'm writing a program with a main class that manages an array of objects of a different class, and I'm having difficulty calling a print() method from this second class, from within the main class.</p> <p>The Main class attempts to call print(), which is in the Unit class. The Unit class looks something like this:</p> <pre><code>public class Unit{ static int numOfUnits = 0; public Unit[] units = new Unit[8]; private int unitID; //constructors are here public void print(){ for (int i = 0; i &lt; units.length; i++) System.out.print(units[i].unitID); } public void add(Unit unit){ mobs[numbofUnits] = unit; numOfUnits++; } } </code></pre> <p>So what I'd like to happen is, through the Main class, I add new Unit objects to the units array. When I'm done adding them (using the call unitToAdd.add(unitToAdd) in the Main class) I would like to call Unit's print() method from within Main.</p> <p>What I don't know is, whether or not, and where, to use the static modifier, how to refer to the variables in the print() method itself (that is, do I use this.unitID, units[i].unitID, etc) and so on.</p> <p>What is confusing me is simply the nature of the print() method. I have setters and getters that work just fine since I completely understand that calling specificUnit.setID() is changing a specific variable for that specific object, but I don't know how to get methods like print() to work.</p> <p>Thanks!</p>
    singulars
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload