如何在 class 中从实例获取属性?

How do I get an attribute from an instance while in a class?

例如,我在 class 中有两个方法,名为 "Wizard":

public class Wizard
{
    public int getAttack()
    {
        return attack;
    }

    public void getHitBy(Object var_of_attacker)
    {
        int attackPower = var_of_attacker.getAttack() - defense;

        if (attackPower > 0)
        {
            health -= attackPower;
            System.out.println(name + " took " + attackPower + " damage!");
        } else {
            System.out.println(name + " managed to completely block the attack!");
        }

        if (health <= 0)
        {
            alive = false;
            System.out.println("Oh, no! \n" + name + " died!");
        }
    }
}

如果我决定制作 class 的两个实例,并且我想让其中一个攻击另一个,我如何从实例中获取攻击属性?

您必须将另一个对象作为参数传递。然后,您可以使用点 (.) 运算符访问参数的方法,而不是 this,使用参数的名称。

考虑一个程序可能有数百个对象;编译器如何知道您要查看哪个 其他对象?

也许我不明白你的问题,因为你已经传递了一个对象?