instanceof keyword usage

后端 未结 8 2262
野性不改
野性不改 2021-02-14 10:44

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:56

    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();
        }
    }
    

提交回复
热议问题