+ 1

Difference between interface and abstract.

When to use interface and when to use interface and when to use abstract class?

18th Nov 2016, 7:07 AM
Jai Verma
Jai Verma - avatar
7 Respuestas
+ 7
Abstract class can contain defined methods and declared methods. Interface can only contain declared methods. An example of a declared method is public static void something(); An example of a defined Method is public static void something() { System.Out.printIn('I am only declared'); } Hence, you use interface or abstract class when you don't know the definition of your methods before now. Use Abstract if two or more child class will have a method of the same definitions. Example, Take a dog and a bird... Both can have a superclass of animal. But how do we decide if animal should be an Abstract or Interface class? That will depend on the types of methods they both will have... - Both dog and bird can move, but a dog walks and a bird flies, since their mode of movement is different, then we can only declare it not define the style of their movement. So we can use either an abstract class or interface to declare move() The second (and probably last) thing we want to do is print who nurtures them. Since both are nurtured by humans, then the method will be public static void nurturedBy(){ System.Out.printIn("I am nurtured by humans"); } Notice we have defined the method, hence the only option we can use is Abstract not Interface. I hope you get the trick...
18th Nov 2016, 12:06 PM
Toheeb
Toheeb - avatar
+ 1
@Toheeb Thank you friend, very good example.
20th Nov 2016, 5:49 AM
Jai Verma
Jai Verma - avatar
+ 1
You use an interface when your class needs to implement multiple classes.However if your class needs to implement only one class, then use abstract classes.
13th Apr 2017, 6:54 AM
Lehlohonolo
Lehlohonolo - avatar
0
@Toheeb Thanks!
4th Jan 2017, 8:25 AM
Rodion Abdurakhimov
Rodion Abdurakhimov - avatar
0
@ Jai and Rodion, you are both welcome.
19th Jan 2017, 5:37 AM
Toheeb
Toheeb - avatar
0
@ Toheeb Sorry, but I think you did a slight mistake: An example of a declared method is public static void something(); This statement is correct! But the next one isn't. An example of a defined Method is public static void something() { System.Out.printIn('I am only declared'); } System.Out.printIn('I am only declared'); ???? Shouldn't it be like: System.Out.println('I am defined'); Please correct me, if I´m wrong! Thanks!
8th May 2017, 1:09 PM
Dinis F
Dinis F - avatar
0
Dinis F My friend that is only a print statement, you can write anything like 'hello world'.
10th Apr 2018, 5:55 AM
Jai Verma
Jai Verma - avatar