检查哪个类

huangapple go评论67阅读模式
英文:

Check which class

问题

我有一个子类的对象,和一个存储这些子类对象的父类数组。

mafia[] obj = new mafia[no_mafia];
detective[] obj1 = new detective[no_detectives];
healer[] obj2 = new healer[no_healers];
commoner[] obj3 = new commoner[no_commoners];

父类被称为 player,基本上在其中存储了每个子类对象。

alive_players[0] = obj[0];//仅为示例

现在我想要检查每个对象的类是否相同,例如:

obj[0].equals(alive_players[rand_var]);

但似乎这不起作用,因为它们都是 player 类的子类(即父类)。我应该如何准确区分它们的类?是否有更好的方法将所有子类对象存储在一个共同的位置?

英文:

I have an object of a child class and an array of the parent class that stores objects of the child classes in it.

mafia[] obj = new mafia[no_mafia];
detective[] obj1 = new detective[no_detectives];
healer[] obj2 = new healer[no_healers];
commoner[] obj3 = new commoner[no_commoners];

the parent class is called player and basically stores each individual objects of each of its child class in it

alive_players[0] = obj[0];//just an example

Now I want to check if the classes of each of their objects are the same for eg:

obj[0].equals(alive_players[rand_var]);

But this doesn't seem to work as they're all subclasses of the class player(which is the parent class). How exactly will I be able to differentiate between their classes? And is there a better way to store all the objects of the subclasses in a common place?

答案1

得分: 1

你需要使用Java instanceof:java的instanceof运算符用于测试对象是否是指定类型的实例。

英文:

You need to use Java instanceof: The java instanceof operator is used to test whether the object is an instance of the specified type

huangapple
  • 本文由 发表于 2020年10月5日 18:00:59
  • 转载请务必保留本文链接:https://go.coder-hub.com/64206427.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定