Instantiating interfaces in Java

前端 未结 14 1536
南笙
南笙 2020-12-07 21:08

I have this interface:

public interface Animal {
    public void Eat(String name);
}

And this code here implements the interface:



        
相关标签:
14条回答
  • 2020-12-07 21:11
    Animal baby2 = new Dog(); //HERE!!!!!!!!!!!!!!!!!!!!!!
    

    Surely you are not instantiating the Animal. You are only referring the Dog instance to it. In java we can take the super class reference.

    0 讨论(0)
  • 2020-12-07 21:12

    The interface Animal is not be intantiated but be implemented by Dog.And a Dog is intantiated

    0 讨论(0)
  • 2020-12-07 21:12

    This is a case of polymorphism, It looks like you are creating 'Animal' object but it is not. You are creating 'Dog' object which is calculated on run time.'Animal' acts as contract. Interface can not be instantiated directly but can be used as type by upcasting its subclass. You can also use anonymous class to instantiate an object as 'Animal' type.

       Animal baby2 = new Dog(); //upcasting polymorphically
       Animal baby3=new Animal(){
          public void Eat(String food){System.out.println("fdkfdfk"); }
       }
        //You can instantiate directly as anonymous class by implementing all the method of interface
    
    0 讨论(0)
  • 2020-12-07 21:13

    What you're observing here is the Dependency inversion aspect of SOLID.

    Your code is depending on the abstraction of the Animal contract by instantiating a concrete implementation of it. You're merely stating, "I'm instantating some object, but regardless of what that object actually is, it will be bound to the contract of the Animal interface."

    Take, for instance, these sorts of declarations:

    List<String> wordList = new LinkedList<>();
    Map<Integer, String> mapping = new HashMap<>();
    

    In both of those cases, the primary aspect of the list and map is that they follow the generic contract for a List and Map.

    0 讨论(0)
  • 2020-12-07 21:14

    When you say:

    Animal baby2 = new Dog();
    

    the reference type is Animal(the interface) which points to a concrete implementations (Dog). The object type Dog is concrete and can be instantiated. In this case, as long as Dog hasanimal point to Dog. a concrete implementation of all the methods in the interface, you can make a reference type of

    If you did something like,

    Animal baby2 = new Animal(); // here you are actually instantiating
    

    this would be invalid because now you are trying to create a concrete object from an abstract implementation.

    0 讨论(0)
  • 2020-12-07 21:15

    Dog is not an interface: Dog is a class that implements the Animal interface.

    There's nothing untoward going on here.


    Note that you can instantiate an anonymous implementation of an interface, like so:

    Animal animal = new Animal() {
        public void Eat(String food_name) {
            System.out.printf("Someone ate " + food_name);
        }
    };
    
    0 讨论(0)
提交回复
热议问题