Instantiating interfaces in Java

喜你入骨 提交于 2019-11-28 04:42:32
Ziyao Wei

No it is not - you are instantiating a Dog, but since a Dog is an Animal, you can declare the variable to be an Animal. If you try to instantiate the interface Animal it would be:

Animal baby2 = new Animal();

Try that, and watch the compiler scream in horror :)

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

Let's consider below code:

interface Cookable {
    public void cook();
}

class Food {
    Cookable c = new Cookable() {
     public void cook() {
         System.out.println("anonymous cookable implementer");
        }
      };
 }

The preceding code creates an instance of an anonymous inner class, but here, the new just-in-time class is an implementer of the Cookable interface. And note that this is the only time you will ever see the syntax:

new Cookable()

where Cookable is an interface rather than a nonabstract class type. Think about it: You can't instantiate an interface, yet that's what the code looks like it's doing. But, of course, it's not instantiating a Cookable object-- it's creating an instance of a new anonymous implementer of Cookable.

You can read this line:

   Cookable c = new Cookable(){}

as "Declare a reference variable of type Cookable that, obviously, will refer to an object from a class that implements the Cookable interface. But, oh yes, we don't yet have a class that implements Cookable, so we're going to make one right here, right now. We don't need a name for the class, but it will be a class that implements Cookable, and this curly brace starts the definition of the new implementing class."

Important to remember for anonymous interface implementers-- they can implement only one interface. There simply isn't any mechanism to say that your anonymous inner class is going to implement multiple interfaces. In fact, an anonymous inner class can't even extend a class and implement an interface at the same time. The innve class has to choose either to be a subclass of a named class and not directly implement any interface at all or to implement a single interface.

So don't be fooled by any attempts to instantiate an interface except in the case of an anonymous inner class. The following is not legal:

Runnable r = new Runnable(); // can't instantiate interface 

whereas the following is legal, because it's instantiating an implementer of the Runnable interface(an anonymous implementation class):

Runnable r = new Runnable() { 
   public void run(){ }
};

You can read my article here.

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.

John
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.

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

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.

The Interface Animal acts as the data type to the class Dog. You're actually instantiating the Dog class not the interface or it's data type.

To have a wider picture :

Animal [] Zoo = new Animal[10] ; // is also correct

but why ?

The whole idea is that in the table above you can put 10 animals of different types. The only conditions for this is that all the animals entering the Zoo must implement the interface Animal .

public interface Animal {
 void Eat();
}
class Wolf implements Animal {  void Eat (){ 
System.out.println("Wolf eats meat ") ;}}

Class Zebra implements Animal{ void Eat (){
System.out.println("Zebra eats the grass ") ;}}

class test {
public static void main (String args []) {

Animal [] Zoo = new Animal[2] ;

Zoo[0] =  new Wolf() ;
Zoo[1] = new Zebra() ;

 //so you can feed your animals in Zoo like this

 for (int i=0 ; i<Zoo.lenght;i++) {Zoo[i].Eat();}
}
}

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
Amol Dixit

Actually you can instantiate the interface. Here is the code you can try

public static void main(String args[]) {
    System.out.println(new Animal() {
        public String toString() {
            return "test";
        }
    });
}

This program runs successfully and prints test Try it.

Here it is just referencing to the interface but instantiation is done by the class only. for e.g

Animanl a = new Dog Animal a - variable is referenced new Dog - now Memory is allocated

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!