Abstract classes vs. interfaces in Java

Posted on 03-01-2013 21:43 by graham
The difference between abstract classes and interfaces in Java is a question that often remains obscure for Java beginners. This article aims to list the similarities and differences between the two, as well as give hints as when to use which.

Interfaces


- They are declared with the interface keyword (obviously...)
- They cannot contain fields
- All methods in an interface must be abstract and public. Note, however, that methods in an interface cannot be marked with the abstract keyword - they are abstract by default and cannot have a body.
- Interfaces are implemented, not extended.

Declaring an interface:
public interface FileReader
{
public String getFileContents();
}

An interface declared above can be implemented by some class that wants to use its functionality:
public class TextFileReader implements FileReader
{
public String getFileContents()
{
// the actual reading of file contents takes place here
...
}
}

Abstract classes


- Must be marked with the abstract keyword.
- May contain both abstract and fully implemented methods.
- May contain fields and properties
- May contain private and protected methods
- They are extended (not implemented) by their child classes

Declaring an abstract class:
public abstract class CustomPageController
{
protected Date dateCreated;
private Integer viewCount;

// abstract method - to be implemented in a subclass
public abstract String getPageTitle();

// non-abstract method - implemented here
public Integer getViewCounter()
{
return ++viewCount;
}

// constructor
public CustomPageController()
{
viewCount = 0;
}
}

A class created this way can be extended the following way:
public class HomePageController extends CustomPageController
{
// abstract methods need to be implemented
@Override
public String getPageTitle()
{
return "My Home Page";
}
}

Similarities


So what do abstract classes and interfaces have in common.
- Both abstract classes and interfaces cannot be instantiated.
- Both represent abstract (unfinished, if you prefer) entities rather than concrete objects.
Comments

 

Add comment

Has this tutorial been helpful to you? Or do you see anything wrong? We appreciate your opinion!
Your comment:
Show formatting hints
HTML is disallowed, but in your text you can use the following markup
  • [code][/code] for a block of code
  • [tt][/tt] for inline code
  • [link]link href|link anchor[/link] for links
  • [b][/b] for bold text
Email:
+ Ask a question
If you have a technical question related to programming and computers, ask it here. Other users will help you solve it!
Unanswered questions
Share your knowledge by helping others solve their problems