+ 1
Difference between interface and abstract.
When to use interface and when to use interface and when to use abstract class?
7 Réponses
+ 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...
+ 1
@Toheeb Thank you friend, very good example.
+ 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.
0
@Toheeb Thanks!
0
@ Jai and Rodion, you are both welcome.
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!
0
Dinis F
My friend that is only a print statement, you can write anything like 'hello world'.