Instantiating interfaces in Java

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

提交回复
热议问题