instanceof keyword usage

后端 未结 8 2390
死守一世寂寞
死守一世寂寞 2021-02-14 10:21

Is using the instanceof keyword against the essence of object oriented programming? I mean is it a bad programming practice? I read somewhere that us

8条回答
  •  隐瞒了意图╮
    2021-02-14 10:57

    Favor polymorphism and dynamic binding to downcasting and instanceof. This is the "OO Way" and enables you to write code that doesn't need to know about subtypes.

    EXAMPLE

    abstract class Animal {
        public abstract void talk();
        //...
    }
    
    class Dog extends Animal {
        public void talk() {
            System.out.println("Woof!");
        }
        //...
    }
    
    class Cat extends Animal {
        public void talk() {
            System.out.println("Meow!");
        }
        //...
    }
    
    class Hippopotamus extends Animal {
        public void talk() {
            System.out.println("Roar!");
        }
        //...
    }
    
    class Main {
    
        public static void main(String[] args) {
    
            makeItTalk(new Cat());
            makeItTalk(new Dog());
            makeItTalk(new Hippopotamus());
        }
    
        public static void makeItTalk(Animal animal) {
    
            animal.talk();
        }
    }
    

提交回复
热议问题