+ 3
How are interfaces different from abstract Classes in Java?
In java, why do we need interface when we have abstract classes or vice versa. How are they different? In which scenarios I would need to use which one? Please give an example or a Real life scenario to elaborate.
5 Antworten
+ 1
//both of the above cat and dog classes extend the abstract class animal. here, animal acts as a blueprint for building classes of similar types.
class mobile implements sleep{
public void goToSleep()
{
System.out.println("Buzzing of");
}
}
interface sleep{
public void goToSleep();
}
//the above interface got applied to a lot more fields like animals and mobiles.
// SUMMARY
/*
ABSTRACT CLASSES can act as blueprints to create multiple clases sharing similar properties.
INTERFACES are like addons. These help you add more functionality to the class irrespective of what the class is meant to do. Over here, you can see that the sleep interface acted as an additional functionality to cat, dog and mobile, no matter even if the "cat and dog classes" had nothing in common with the "mobile class".
A good example is the "Runnable" interface in java. You can learn about it later in the sololearn java course.
*/
+ 1
ɴᴜʟʟ thnx but it's incomplete. It's only coded till Line 34
+ 1
Subhadeep Mandal maybe sololearn is having some problems. I am pasting the thing here
// SUMMARY BELOW
public class Program
{
public static void main(String[] args) {
dog doggo = new dog();
doggo.speak();
doggo.goToSleep();
cat kitty = new cat();
kitty.speak();
kitty.goToSleep();
mobile mob = new mobile();
mob.goToSleep();
}
}
abstract class Animal{
String sound;
void speak()
{
System.out.println(sound);
}
}
class dog extends Animal implements sleep{
public dog()
{
this.sound="woof!";
}
public void goToSleep()
{
System.out.println("gr...");
}
}
class cat extends Animal implements sleep{
public cat()
{
this.sound="meow";
}
public void goToSleep()
{
System.out.println("PURRrrr!");
}
}
0
Hope this helps..
https://www.tutorialspoint.com/when-to-use-an-abstract-class-and-when-to-use-an-interface-in-java
edit:
for more, search bar will give more related answers..
0
An example to show difference between Interfaces and Abstract classes in Java
https://code.sololearn.com/cl1N2L1XSocE/?ref=app