Why would you declare an Interface and then instantiate an object with it in Java?

后端 未结 10 1317
再見小時候
再見小時候 2020-12-13 06:41

A friend and I are studying Java. We were looking at interfaces today and we got into a bit of an discussion about how interfaces are used.

The example code my frie

10条回答
  •  隐瞒了意图╮
    2020-12-13 07:34

    Because you don't really care what the implementation is... only what it's behavior is.

    Say you have an animal

    interface Animal {
        String speak();
    }
    
    class Cat implements Animal {
    
        void claw(Furniture f) { /* code here */ }
    
        public String speak() { return "Meow!" }
    }
    
    class Dog implements Animal {
    
        void water(FireHydrant fh) { /* code here */ }
    
        public String speak() { return "Woof!"; }
    }
    

    Now you want to give your kid a pet.

    Animal pet = new ...?
    kid.give(pet);
    

    And you get it back later

    Animal pet = kid.getAnimal();
    

    You wouldn't want to go

    pet.claw(favorateChair);
    

    Because you don't know if the kid had a dog or not. And you don't care. You only know that --Animals-- are allowed to speak. You know nothing about their interactions with furniture or fire hydrants. You know animals are for speaking. And it makes your daughter giggle (or not!)

    kid.react(pet.speak());
    

    With this, when you make a goldfish, the kid's reaction is pretty lame (turns out goldfishes don't speak!) But when you put in a bear, the reaction is pretty scary!

    And you couldn't do this if you said

    Cat cat = new Cat();
    

    because you're limiting yourself to the abilities of a Cat.

提交回复
热议问题