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.
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.
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.
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.
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();
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With