Instantiating interfaces in Java

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

提交回复
热议问题