英文:
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
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论