Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Accessing objects of other classes

Tags:

java

object

class

I've recently picked up Java and have run into a problem. I have several files with different classes, but I can't figure out how I can access objects of the other classes in files other than the one they were declared in. For example:

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

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

I'm not sure how I can access these objects of other classes effectively from other files and classes themselves? I know I could make the objects static and then access them as variables through the class they were made in, but that seems rather counter-intuitive? I come from a less object-oriented programming background so I'm still trying to understand java's style of programming.

like image 598
Lucas Penney Avatar asked Dec 30 '12 04:12

Lucas Penney


People also ask

How do you access objects of another class?

To access the members of a class from other class. First of all, import the class. Create an object of that class. Using this object access, the members of that class.

How do I use another class object in Python?

If we have two different classes and one of these defined another class on calling the constructor. Then, the method and attributes of another class can be accessed by first class objects ( i.e; objects within objects ). Here in the below example we learn to access object (its methods and attributes) within an object.

How do you access a class object in Python?

To access the method of a class, we need to instantiate a class into an object. Then we can access the method as an instance method of the class as shown in the program below. Here through the self parameter, instance methods can access attributes and other methods on the same object.


1 Answers

A good place to start would be to pass in the player you want to attack "when" the monster attacks.

battle.java

public class Battle {

  public static void main(String[] args) {
    Player player = new Player();
    Monster monster = new Monster();
    monster.attackPlayer(player);
  }
}

player.java:

public class Player 
{
    public int getLocation()
    {
         return 2;
    }
}

monster.java:

public class Monster
{
    public void attackPlayer(Player player)
    {
        player.getLocation();
    }
}
like image 70
alexwen Avatar answered Sep 28 '22 09:09

alexwen