+ 1
Understanding the Difference between Abstract and Interface
For those who have doubts about this topic.
4 odpowiedzi
+ 9
If you know the answer why did you post the question?
+ 8
Noted
+ 2
@Yerucham read the description. It's a topic, not a question. Just helping out who does not know
+ 1
To understand both interfaces and abstract classes, you must understand what is an abstract method. An abstract method is the defined-only method, that keeps waiting for you to implement it in another inherited class. It's useful to avoid useless implementations when you clearly would need to override a method.
ex:
public class Human{
public void voice( ){
System.out.println("Human has a voice");
}
}
public class Man extends Human{
public void voice( ){
System.out.println("Man has a low voice");
}
}
As you see, the voice method was defined, but still implemented with no reason in the Human class as it's gonna be overridden in the inherited class Man.
We could then use the voice method as an abstract method to be implemented ONLY in the inherited class. We would only define it in the class Human.
As an abstract class is a class with at least one abstract method, using voice method as an abstract method makes Human class automatically abstract, so, we should write it like this:
public abstract class Human{
public abstract void voice( );
}
public class Man extends Human{
@Override
public void voice( ){
System.out.println("Man has a low voice");
}
}
Now that you learned what an abstract class is, you must learn that an interface is a FULLY abstract class, where its attributes are static and final implicitly(constants) and its methods abstract and public also implicitly.
public interface Human{
void voice( ); //no need to use access modifier
void printInfo( );
int NUMBER_OF_EYES = 2; //static and final implicitly
}
public class Man implements Human{
@Override
public void voice( ){
System.out.println("Man has a low voice");
}
@Override
public void printInfo( ){
System.out.println("Num of eyes a man have: " + NUMBER_OF_EYES);
}
}