+ 2

What's the diffrence between abstract classes and interfaces in java?

Interfaces are implictly abstrcat and contains methods without method bodies. Abstract classes also has methods without method bodies. So what's the diffrence?

22nd Jul 2017, 5:12 AM
Viraj Singh
Viraj Singh - avatar
1 Réponse
+ 1
An interface is a fully abstract class. If you're implementing an interface, you have to override all methods in there. Like an abstract class, it cannot be instantiated. Often you could use an abstract class instead of an interface, but if you want to use an abstract class, you must inherit from it. Because you can implement as much interfaces as you want, it's better to use them instead of inherit from an abstract class. If you inherit from a class, this class is the superclass of your class which is the subclass. A subclass takes all methods of the superclass and uses them. Then, you can override some methods, for example you want to give your class a specific behaviour. If your superclass is the class names "animals", you could inherit from your brand new class named "elefant". An elefant is an animal, so it eats, sleep and so on. Bit there are differences too, an elefant has a special "voice". If you have a method "speak" you want to override it to give your elefant a voice. That's a good example of abstract methods:You do not know which voice your animal will have when your writing the "animal class", so you make your method abstract. If you aren't looking forwards to write your project with other programmers, you could write the "voice" method anyway without the abstract keyword and override it, but the possibility of bugs is bigger, because you could forget it. That's all an example.😊 You can only inherit from one class while you're able to implement as many interfaces as you want. If that specific interface fits perfectly into your uses, it's better to implement it instead of "wasting" the place for another superclass.
22nd Jul 2017, 2:07 PM
Jonas Schröter
Jonas Schröter - avatar