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

后端 未结 10 1308
再見小時候
再見小時候 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:25

    You're really asking: what reference type should I use?

    Generally you want to use as general a reference type as possible that still gives you access to the behavior that you need. This means any of the interfaces or parent classes of your concrete type, rather than the concrete type itself. Of course, don't take this point too far -- for example, you certainly don't want to declare everything as an Object!

    Consider these options:

    Set<String> values1 = new TreeSet<String>();
    TreeSet<String> values2 = new TreeSet<String>();
    SortedSet<String> values3 = new TreeSet<String>();
    

    All three are valid, but generally the first option of values1 is better because you will only be able to access the behavior of the Set interface, so later you can swap in another implementation quite easily:

    Set<String> values1 = new HashSet<String>();
    

    Beware of using the second option values2. It allows you to use specific behavior of the TreeSet implementation in such a way that swapping in a different implementation of Set becomes more difficult. This is fine as long as that's your goal. So, in your example, use a Car or Bike reference only when you need access to something that's not in the IVehicle interface. Be aware though that the following would not work:

    TreeSet<String> values2 = new HashSet<String>(); // does not compile!
    

    Still there are times when you need access to the methods that are not in the most general type. This is illustrated in the third option values3 -- the reference is more specific than Set, which allows you to rely on the behavior of SortedSet later.

    TreeSet<String> values3 = new ConcurrentSkipListSet<String>();
    

    The question about reference types applies not only where variables are declared, but also in methods where you have to specify the type of each parameter. Fortunately the "use as general a reference type as possible" rule of thumb applies to method parameters, too.

    0 讨论(0)
  • 2020-12-13 07:26

    It doesn't matter there.

    Where it really matters is in other interfaces that need to operate on IVehicle. If they accept parameters and return values as IVehicle, then the code will be more easily extendible.

    As you noted, either of these objects can be passed to a method that accepts IVehicle as a parameter.

    If you had subsequent code that used Car or Bike specific operations that were used, then it would be advantageous to declare them as Car or Bike. The Car and Bike specific operations would be available for each of the relevant objects, and both would be usable (i.e. could be passed) as IVehicle.

    0 讨论(0)
  • 2020-12-13 07:29

    With "IVehicle modeOfTransport1 = new Car();", methods owned only by Car are not accessible to modeOfTransport1. I don't know the reason anyway.

    0 讨论(0)
  • 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.

    0 讨论(0)
  • 2020-12-13 07:34

    well interfaces are behaviors and classes are their implementation so there will be several occasions later when you will program where you will only know the behaviors(interface). and to make use of it you will implement them to get benefit out of it. it is basically used to hiding implementation details from user by only telling them the behavior(interface).

    0 讨论(0)
  • 2020-12-13 07:40

    Declaring interfaces and instantiating them with objects allows for a powerful concept called polymorphism.

    List<IVehicle> list = new ArrayList<IVehicle>();
    list.add(new Car());
    list.add(new Bike());
    
    for (int i = 0; i < list.size(); ++i)
        list.get(i).doSomeVehicleAction();   // declared in IVehicle and implemented differently in Car and Bike
    

    To explicitly answer the question: You would use an interface declaration (even when you know the concrete type) so that you can pass multiple types (that implement the same interface) to a method or collection; then the behavior common to each implementing type can be invoked no matter what the actual type is.

    0 讨论(0)
提交回复
热议问题