is interface a class in java code example
Example 1: java interface
public interface Exampleinterface {
public void menthod1();
public int method2();
}
class ExampleInterfaceImpl implements ExampleInterface {
public void method1()
{
}
public int method2()
{
}
}
Example 2: 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.