The first thing to do is to remember that no one learns about object-oriented programming concepts without getting lots of practice in writing code. If you've r you're confused, that may be a good thing. It means you've understood enough to know how complicated this stuff is. The more code you write, the more comfortable you'll become with classes, interfaces, and all these other ideas.
The next thing to do is to sort out the differences in the way you declare abstract methods. Here’s the story.
In an Ordinary (Non-Abstract) Class | In an Interface | In an Abstract Class | |
Are abstract methods allowed? | No | Yes | Yes |
Can a method declaration contain the abstract keyword? |
No | Yes | Yes |
Can a method declaration contain the default keyword (meaning "not abstract")? |
No | Yes | No |
With neither the abstract nor the default |
Not abstract | Abstract | Not abstract |
Interfaces and abstract classes are similar beasts, and the new features in Java 8 made them even more similar than in previous Java versions. But the basic idea is about the relationships among things.
- Extending a subclass represents an is a relationship.
- Implementing an interface represents a can do relationship.
public class Dog extends HousePet
you can't also make Dog
extend a Friend
class. But you can make Dog
implement a Befriendable
interface. And then you can make the same Dog
class implement a Trainable
interface.
And, if you want an even more tangible difference between an interface and an abstract class, here’s one for you: An interface can't contain any non-static, non-final fields.
So there. Interfaces and abstract classes are different from one another. But if you're new at the game, you shouldn't worry about the difference. Just read as much code as you can, and don't get scared when you see an abstract method. That's all there is to it.