can you create object of interface in java code example
Example: can interface have objects in java
No, you can never instantiate an interface in java. You can, however, refer to an object that implements an interface by the type of the interface.
interface Animal{
void eat();
}
You cannot do this “Animal animal = new Animal();” Bcoz in “interface” class don’t have Constructor .
Now consider.
class Lion implements Animal
{
@Override
void eat(){ System.out.println(“I eat only non-veg”);}
}
class Test(){
Animal animal = new Lion();
animal.eat();
}
Object of “Lion” is created and “Animal” hold the reference(address) of the Lion’s object.