+ 1
Is instantiation possible with the INTERFACE keyword OR NOT ???
hi all ! 2 questions : 1) I thought that instantiation was not possible with interfaces (implements) ??? so why did we succeed to create an object and apply a method to them ??? look ! interface Animal { public void eat(); public void makeSound();} class Cat implements Animal { public void makeSound() { System.out.println("Meow");} public void eat() { System.out.println("omnomnom");}} public class Program { public static void main(String[] args) { Cat c = new Cat(); c.eat(); c.makeSound();}} // print omnomnom & Meow 2) What does INTERFACE is used for exactly ? i m sure to understand . thanks for explanation !
5 Réponses
+ 4
It is the class that is instantiated and not the interface. The class implements the interface.
+ 3
I am not sure if I understand your first question. It is not possible to create an object of an interface (same with abstract classes). But a class can implement interfaces. As much as you want. If you have two or more interfaces and want to implement them all, you can do it.
For the second question you can look here:
https://www.quora.com/What-is-the-need-of-interface-in-Java
+ 3
Btw: You need interfaces to use lambda expressions.
https://code.sololearn.com/c5ZmQguR1rPp/?ref=app
+ 1
1. you can't create an object from interface like this Animal cat=new Animal(); but you can use the class that implement the interface Animal c=new Cat();
2. to make sure certain class has predefined name for a method to use, its also ties with polymorphism where as in this Example Cat can be recognize as Animal.
interface Animal{
public String makeSound();
}
class Cat implements Animal{
public String makeSound(){
return "Meow";
}
}
class Dog implements Animal{
public String makeSound(){
return "Woof";
}
}
class Program{
public static void main(String[]args){
Cat c=new Cat();
Dog d=new Dog();
sound(c);
sound(d);
}
static void sound(Animal a){
System.out.println("it says "+a.makeSound());
}
}
0
Interface is a template which tells what can be done without specifying how it has to be done. Animal is an interface which tells that animal can eat and make sound. Now a class Cat implements the behavior designed by Animal and gives definition of the eat and make sound method and in last you are creating the object of the cat class which is calling the implemented method eat and makesound.