How to check if a class extends another

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{
    //Code to attack enemy here
}

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.

+5
source share
8 answers

Edit

if(enemy.getSuperclass().equals(Flying)){

to

if(enemy instanceof Flying){

, enemy , Flying, , Flying (, , enemy , Flying ).

instanceof , , ( ), , , (, , Unit sub-class — GroundBased something — Unit). , , .

+11

instanceof.

    if(enemy instanceof Flying){
        System.out.print("Soldiers cant attack flying units");
    }
    else{
        attack(enemy);
    }
+2

instanceof . , , .

, instanceof null.

B A

   public class test
   {
    public static void main(String[] args)
    {
        A a = new B();
        B b = new B();
        if(a instanceof A)
            System.out.println("B derived from A");
        if(b instanceof A)
            System.out.println("B derived from A");
    }
   }
+2
if (enemy instanceof Flying)
   ...
+1

:

if (enemy instanceof Flying)
+1

, instanceof .

instanceof . , , , .

, :

if(enemy instanceof Flying){
   System.out.print("Soldiers cant attack flying units");
}
else{
    attack(enemy);
}
+1

if(enemy instanceof Flying) {}

+1

This is a designer smell. The basic requirement is to work for the visitor template , but you should also use polymorphism better than this before you even get to the visitor.

0
source

All Articles