What is the difference between abstract class and interface?

Recommended Answers

All 4 Replies

Try this link. Its the Abstract Methods and Classes page of the Inheritance section of the Java Tutorial. There is a link on there to the Interfaces page.

Basically though an Interface is a collection of undefined methods intended to allow standardization between classes which are not similar enough as to justify them inheriting from the same abstract parent class. Compare AbstractButton to JButton, JMenuItem and JToggleButton. Then compare the relationship between those classes andthe different interfaces listed on their API pages.

An abstract class can have instance methods that implement a default behavior. An Interface can only declare constants and instance methods, but cannot implement default behavior and all methods are implicitly abstract. An interface has all public members and no implementation. An abstract class is a class which may have the usual flavors of class members (private, protected, etc.), but has some abstract methods

An abstract class is a regular class except that one or more methods may not have been defined. Ex: Think getSalary() method in Employee class, where different employees have different calculations for their salaries.

An interface, on the other hand, is a specification to be complied with, for specific functionality. Ex: to use threads in a class, it must implement runnable (not quite, it can extend Thread, but that is not a good way!). I think a sortable object must implement the comparable interface.

Not being instantiable is another difference with Interfaces.

You only need to make your class abstract if it contains abstract methods, you could make your class abstract if you wanted anyway.

Implementing interfaces ensures your classes contain methods and variables they are supposed to.

The only time I really use interfaces is for Listener Interfaces, such as MouseListener, MouseMotionListner, and importantly ActionListener, which has just 1 method (actionPerformed(ActionEvent e)) to implement.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.