I have seen variants of this question, but none of them really affect my problem.
Let's say I'm building an army with classes. At the top of my Inheritance structure, I have an abstract Unit class . Then add the abstract Flying class ", Ground " and Building ", which expands the unit. Then we will create a specific class " Helicopter "and Jet ", which extends Flying. As well as a specific class of Soldiers "and Tank ", which extends the Earth. And, finally, " HQ " and " Supply ", which expands the building.
The following is the method under the Soldier class :
public void attack(Unit enemy){
if(enemy.getSuperclass().equals(Flying)){
System.out.print("Soldiers cant attack flying units");
}
else{
}
I want the enemy to be any form of unit. This is due to the fact that a soldier must be able to attack both buildings and other ground units. However, I do not want soldiers to be able to attack flying objects.
The obvious problem is that since I declared enemy as Unit , he does not know which subclass he belongs to, and therefore he is trying to find a SuperClass for Unit which does not exist.
I'm sure I can have a getter for each device that manually set which type of device it is ... but it works more and doesn't seem to be effective.
source
share