I
I
Igor-Novikov2020-01-30 17:09:26
Java
Igor-Novikov, 2020-01-30 17:09:26

How to understand what type the object was?

I can not understand one moment on polymorphism. It can be thought of as a game.
Let's say we have game character types that inherit from the generic Hero type.

class Hero {

}

class Hero1 extends Hero {

}

class Hero2 extends Hero {

}

class Hero3 extends Hero {

}

class Hero4 extends Hero {

}

class Hero5 extends Hero {

}

class Hero6 extends Hero {

}

We can form a team from three types of characters by passing them to the constructor.

public class Test {
  public static void main(String[] args){
    Hero2 hero2 = new Hero2();
    Hero4 hero4 = new Hero4();
    Hero6 hero6 = new Hero6();

    Team team = new Team(hero2,hero4,hero6);
  } 
}

class Team {
    public Team(Hero hero1, Hero hero2, Hero hero3){
      //
    }
}


Team constructor with general parameters Hero because we don't know what type of characters the players will choose.
How, after creating the class, to understand which characters the players passed to the constructor?
Only explicitly cast to existing types if possible and if the type does not match, catch exceptions?

Answer the question

In order to leave comments, you need to log in

3 answer(s)
I
Israpil Akhmedov, 2020-01-30
@Igor-Novikov

Can an operator help you instanceof?

C
Cheypnow, 2020-01-31
@Cheypnow

The essence of polymorphism is precisely that there would be no need to recognize a specific type. It is enough to implement a single interface, and write different logic in the implementation.

K
Konstantin Malyarov, 2020-01-30
@Konstantin18ko

class Team {
    public Team(Hero1 hero1, Hero2 hero2, Hero3 hero3){
      //
    }
}

Isn't that easier?

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question