Hello !

How can I get a class out of the collection (by example)

There is an abstract class Игрок :

 public Player(String firstName, String lastName, int age) { this.firstName = firstName; this.lastName = lastName; this.age = age; } 

There is a class Вратарь

 public GoalKeeper(String firstName, String lastName, int age, int handling, int aerialAbility) { super(firstName, lastName, age); this.handling = handling; this.aerialAbility = aerialAbility; } 

Later, I create an object and place it in the Игрок type collection (abstract class)

 players = new ArrayList<Player>(); players.add(new GoalKeeper("Олег", "Газманов", 11, 44, 35)); 

How can I get data from the Вратарь class from this collection? Thank !

    2 answers 2

    It is necessary to check and type:

     Player player = players.get(0); //или другой индекс if (player instanceof GoalKeeper) { GoalKeeper goalKeeper = (GoalKeeper) player; //... } 
    • Thank you human, great!) - kxko

    You can use instanceof , but, in my opinion, it’s better to add an enumeration with possible player positions:

     enum Position { GK, DC, FW // etc } abstract class Player { abstract Position getPosition(); ... } class GoalKeeper { @Override Position getPosition() { return Position.GK; } ... } 
    • And then how to use this Position? Yes, and what for he needed if tied tightly to the class? Same instanceof side view. - Sergey
    • Use as well as instanceof - depends on the intentions of the author. The advantage of this approach is the possibility of using an enumeration in switch and UI interface elements (for example, as values ​​for drop-down lists) + this approach is more appropriate for OOP: we work with a higher level abstraction, rather than with checking for class correspondence. This is my opinion, if instanceof sufficient, then use it. - Pavel Parshin