You're probably just wanting something like this:

player.java:
public class Player 
{
    public static void main(String[] args) {
        Player player = new Player();
        Monster monster = new Monster();
        monster.attackPlayer(player);
    }
    public int getLocation()
    {
         return 2;
    }
}

monster.java:
public class Monster
{
    public void attackPlayer(Player player)
    {
        player.getLocation();
    }
}

Hope that helps/makes sense!

Answer from awolfe91 on Stack Overflow
🌐
Sololearn
sololearn.com › en › Discuss › 1270274 › how-to-access-object-in-another-class
How to access object in another class. | Sololearn: Learn to code for FREE!
If i declared any object in class A and i want to access it from class B.How can i access the object? javaobject · 10th May 2018, 5:52 PM · Faisal Rahman · 2 Answers · Answer · + 1 · If I take your question literally you have a method (the access modifier doesn’t really matter) and you want to access a method on another object: private void myMethod () { otherObject.otherMethod ();} Obviously, in order to do so you’ll have to pass that object into your class.
Discussions

[JAVA] How to use an object from another class
You really need to review what an object actually is. There have already been a few comments that have given you the answer, but they're glossing over what I feel is a fundamental misunderstanding on your part, so I'll try to explain what you're doing, why it's wrong, and what you can do instead, by example. You can't subtract two objects without defining what the subtraction operator, -, means for them. For instance, you could have two bank account objects. Inside the objects could be a name, address, and a balance. If you wanted to see the difference in account balances, you can't do just the following: accountObject1 - accountObject2 The reason for this is that the compiler doesn't know what it means to subtract one object from another. If the balance field of each object is a public member, you could instead do the following: accountObject1.balance - accountObject2.balance Note that generally it is not recommended to access objects' members in this way, most will recommend the usage of getter and setter methods. More on reddit.com
🌐 r/learnprogramming
12
43
March 10, 2013
How do I access an object from another class in java? - Stack Overflow
How do I access an object from another java file? Class1.java: public class Class1 { Classx obj = new Classx(); //Classx is another public class, in another file, i'm just making an object in Class... More on stackoverflow.com
🌐 stackoverflow.com
January 7, 2021
java - Access Objects from another class? - Stack Overflow
I am currently on my way to learning java. And im making a tiny card game like hearthstone for experimental purposes :) But ive run into a issue. Im creating all the cards/"minions" in another cla... More on stackoverflow.com
🌐 stackoverflow.com
How can access a object in main class from another class in java? - Stack Overflow
I have a main class and two sub class in java language.how can access xx in class Y?please help me ,I need it in my project. More on stackoverflow.com
🌐 stackoverflow.com
🌐
Quora
quora.com › How-can-I-access-an-object-from-another-method-in-Java
How to access an object from another method in Java - Quora
Accessing an object created or held in one method from another method in Java is a matter of scope and design. Below are practical patterns with concise examples and when to use each. 1) Use instance fields (recommended for state you need across methods) Make the object a field of the class so all ...
🌐
Reddit
reddit.com › r/learnprogramming › [java] how to use an object from another class
r/learnprogramming on Reddit: [JAVA] How to use an object from another class
March 10, 2013 -

I'm fairly new to Java programming, and I've hit a bit of a wall trying to work out how to use two variables called from another .java file.

public static double distance(DataObject object1, DataObject object2)

DataObject.java is another file, and I'm supposed to be using object1 and object2 to determine the distance between the two. I'm all good with working out the math behind doing so, but I have no idea how to actually USE object1 and object2. Just slapping double sum = object1 - object2 sends JAVA into a tiffy.

Can anyone give me an idea of how to use these two variables? Right now I'm simply doing

if ((((object1 - object2)2)Math.sqrt)) { return true; } else { return false; }

edit: I should have mentioned that this is for an assignment. I'm not sure if copying/pasting the entire code would be a problem in their eyes; plagiarism etc. I'll suss that out tomorrow. If anyone has any decent links to some good, beginners Java sites that might give me a good idea I'd appreciate it! I've scoured online and slowly getting some idea of how to do it.

🌐
Quora
quora.com › How-do-I-access-a-variable-from-another-class-in-Java
How to access a variable from another class in Java - Quora
Answer (1 of 4): You do that using an object of that class, though static variables can be accessed without an object, using the class name. For normal variable: 1st create an object, ClassName obj = new ClassName(); now access using obj.variableName For static variables: Simply use ClassNa...
🌐
CodingTechRoom
codingtechroom.com › question › -access-object-another-class-java
How to Access an Object from Another Class in Java - CodingTechRoom
Instantiate the class where the object was created within the accessing class. Ensure that the methods or properties accessed are public or accessible based on Java's access control. Utilize getter methods to access private variables. Mistake: Attempting to access private variables directly ...
Top answer
1 of 2
2

Some hints or advice about your code that help you :

1. try to define your setter and getters for encapsulation purposes ,and having access to each field.

for example:

private int ID;

getter method is

public int getID(){
       return this.ID;
  }

setter method is

public void setID(int newID){
       this.ID = newID;
 }

2. Instead of having displayMinionData() , it is good practice to override toString method

For example if your variables are :

   private String came;
   private String city;

   public String toString(){
         return name + " " + city;
   }

I am not sure what you by accessing the solider in main method:

but you have this

Minion soldier = new Minion(0, "Soldier", "Human", "The First minion", 2, 1, 1);

As I told you

1. you can printout the whole info by using overridden toString on the console

2. you can extract each portion of the soldier variable by using getters

3. you can update each portion of the soldier variable by using setters

sample for toString:

System.out.print("Info about the current soldier is " + soldier.toString());

sample for getters:

System.out.println("ID:" + soldier .getID()):

sample for setters:

   int newID = 123456789;
   soldier.setID(newID);
   System.out.println("The new id of current soldier is " + soldier.getID()):
2 of 2
0

If you want to access individual fields (such as name, health, attack, etc) you will have to add public access for them. By declaring them private, you made them only visible inside the Minion class. That's not a bad thing! It's best practice to keep fields private, but provide public getters / setters to get or set the values, respectively. This ensures they can't be changed except by specific methods that you have written.

To write a getter/setters, make two methods for each field which needs public visibility:

public int getID(){
    return this.ID;
}

public void setID(int ID){
    this.ID = ID;
}

Then, you can create a Minion (as you have) and do something like System.out.println(soldier.getName());

(By the way, it's convention in Java to capitalize classes (like Minion and MinionTracker) and camelCase objects (like soldier or minionName)

Find elsewhere
🌐
Stack Overflow
stackoverflow.com › questions › 26926316 › how-can-access-a-object-in-main-class-from-another-class-in-java
How can access a object in main class from another class in java? - Stack Overflow
Create a function inside Y class with a type X parameter, then you can call this function from your Main class and change xx value. import class X,Y; public static void main(String[] args) xx=new X; example=new Y; xx=example.changeXValue(xx); ...
Top answer
1 of 2
2

I believe the option that follows Object-Oriented Programming principles best is to pass the actual Player in as an argument, instead of just the money.

Basically, passing just the player's money in instead of the player themselves is like just handing your wallet over to the cashier. You wouldn't do that, right?

This way, the clerk can ask the customer if they have enough money by calling player.getMoney(), and the customer can tell them the answer.

After making the purchase, the player can remove the money from their wallet themselves when the clerk asks them to via player.setMoney().

Now, you asked in a comment about "passing the actual player as an argument without creating a new object of the player class." Java passes arguments by value, and all objects' values are simply the address that hold the information for that particular instance.

So for Player p1 in Beta, let's pretend all of p1's information is stored in a block starting at...let's say, address 21343. In this case, the variable p1 only contains that single number, 21343.

Since Java passes by value, then when you call s1.clerk(Player player), the player variable will also contain 21343. Since it's editing the items contained at the same address, you've essentially passed on p1 itself instead of creating a new Player. In short, the clerk and the main method work with the same object.

The fact that Java passes by value is also why passing just the player's money in doesn't adjust it automatically: The money is an int rather than an object. Since it's an int, when you pass it to the clerk, you're just saying "Hey, clerk, this is the amount of money being worked with." But the clerk has no idea who the money belongs to, so while it can take money, or even give it some, it's essentially just setting it down on the counter, and it's the responsibility of the player to pick it up from there when they're done. By passing in the player instead, the clerk knows who the money belongs to because it's actually asking the player how much money they have.

2 of 2
-1

Another potential solution would be to make p1 and s1 static variables in the Beta class. It'd look something like this:

public class Player
{
    public static Player p1;
    public static Shop s1;

    public static void main(String[] args)
    {
        p1 = new Player("Test");
        s1 = new Shop();

        p1.setMoney(100);
        s1.clerk(p1.getMoney());
    }
}

From there, you'd import the Beta class in Shop, then call Beta.p1 in Shop to access p1. Hope this helps!

🌐
Coderanch
coderanch.com › t › 392636 › java › call-object-class
how to call object in another class? (Beginning Java forum at Coderanch)
October 13, 2002 - One contains the constructor (has 2 parameters), private variables, get and set methods. Note that every class has one or more constructors. If you have not defined one in the class description (the .java file), then the compiler creates a "default" no-argument constructor for your class. I instantiate an object in another class ...
🌐
Greenfoot
greenfoot.org › doc › howto-1
How to Access One Object From Another
Now, add a method to the Space class to retrieve the value of "theCounter" so it can be accessed by the rocket: public Counter getCounter() { return theCounter; } We can then access the world from the shot, and then call the getCounter method on the world to obtain a reference to the counter; finally, we can call the bumpCount method on the counter reference!
🌐
YouTube
youtube.com › android studio
How to Access the Variables and Methods of another Java Class - YouTube
Demonstration of the use of mother Class variables and methods in the Child Class facilitated by the "extends" keyword.
Published: March 13, 2020
Views: 3K
🌐
Stack Overflow
stackoverflow.com › questions › 28780690 › how-to-access-an-object-created-in-one-class-in-another-class
java - How to access an object created in one class in another class - Stack Overflow
System.out.println(new A().Obj);//or define Obj as static in A class. Note - You should encapsulate your Obj and access it via getter method. ... You should use provide a get method or use that object in static method as well.
Top answer
1 of 2
1

Assume the Brand is a lightweight objects and Run is heavyweight then creating a field with the container for the lightweight objects and hiding it is a good idea.

But the Brand needs access the container it belongs to it could be done with the mapping but we are simply inject the Run to the Brand so it's better implement the Runable or annotate it with JSR330. And accessing the container through the Run in the normal way.

class MainClass {
  public static void main(String[] args) {
    Run r = new Run();
  }
}

class Run {
  private Container con1 = new Container();

  public Run() {
    Brand cola = new Brand("Coca Cola");
    Brand pepsi = new Brand("Pepsi");

    // Creates the container object "con1" and adds brands to container.
    add(cola);
    add(pepsi);
  }
  public void add(Brand b){
    con1.addToList(b);
    b.setRun(this);
  }

  public Container getContainer() {
    return con1;
  }
}

class Brand {
  // In this class I have a method which needs to accsess the con1 object
// containing all the brands and I need to access the method
  private String name;
  private Run run;

  public Brand(String name){
    this.name = name;

  }
  public void brandMethod() {
    if(getRun().getContainer().methodExample()) {        // Error here. Can't find "con1".**
      System.out.println("Method example returned true.");
    }
  }


  public Run getRun() {
    return run;
  }

  public void setRun(Run run) {
    this.run = run;
  }
}

class Container {
  // This class is a container-list containing all brands brands
  private ArrayList<Object> list = new ArrayList<Object>();

  public boolean methodExample(){
    return false;
  }

  public void addToList(Object o) {
    list.add(o);
  }
}
2 of 2
0

If you want to get the object created in classB a static field should do the job

public class classB {

  public static objectCReference;

  public classC getObject(String getstring){
     objectCReference =  new classC(getstring);
     return objectCReference;
  }
}

Then you can access the reference in A

public classA {
  int a = 0.5;

  if (classB.objectCReference != null) { // Make sure to null check 
    classB.objectCReference.methodC(a); 
  }

}

Also please follow the language conventions and start your class names with capital letters.

🌐
Stack Overflow
stackoverflow.com › questions › 5505257 › access-an-object-method-created-in-main-class-from-another-class
java - Access an object method created in main class from another class - Stack Overflow
April 1, 2011 - If you want the method to be accessed via the class then you would need to create the method static, so it is a class method and not an instance method, so you can call it like: