Instantiating interfaces in Java

前端 未结 14 1537
南笙
南笙 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:16

    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.

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

    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.

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

    Java 8 let you use, the functional interface,

    @FunctionalInterface // this is not mandatory 
    interface A{
        void m1(); // only one abstract method allowed for functional interface
    }
    
    class Main{
       public static void main(String a[]){
    
          // old usage
          A a1 = new A(){
            @Override
            public void m1(){
               System.out.println("Call Me normally");
            }
          };
    
          a1.m1();
    
          // new in java 8, functional interface
          A a2 = ()-> System.out.println("Call Me as functional interface");
          a2.m1();
     
       }
    }
    
    0 讨论(0)
  • 2020-12-07 21:27

    You can't instantiate an interface. The functionality can be considered similar to that of an abstract class. You can have a reference to the interface but you don't create an object of interface. If you do something like this....

    Animal a = new Animal(); The compiler will show an error- "Cannnot instantiate the type Animal".

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

    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.

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

    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();}
    }
    }
    
    0 讨论(0)
提交回复
热议问题