What is the difference between interface and abstract | Sololearn: Learn to code for FREE!
New course! Every coder should learn Generative AI!
Try a free lesson
+ 2

What is the difference between interface and abstract

JAVA

12th Dec 2017, 11:06 AM
Alagiri Buddhar
Alagiri Buddhar - avatar
2 Answers
+ 11
interface is fully abstract class, all methods in interface are abstract and interface can't have fields. Abstract class can have fields and non - abstract methods. Class can extends one class but more interfaces
12th Dec 2017, 11:17 AM
Vukan
Vukan - avatar
+ 2
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); } }
12th Dec 2017, 11:49 AM
Jonathan Álex
Jonathan Álex - avatar