I was just sitting here studying Java Strings. I’ve never actually ‘studied’ the subject, rather I’ve just picked up on what I have been exposed to. Anyway, all of a sudden a thought popped into my head.
- “What the difference between an Abstract class and an interface?”
- “Are they the same thing?”
- “How would I explain the difference?”
Of course I had to look up the answer in google, and it appears to be a difference of intended application.
An abstract class is an incomplete class. It provides some state fields, and specifies some behaviour. You could say it was an ‘incomplete implementation’. You would need to create a sub-class that fills in the blanks, this would be a ‘concrete class’ that you can then instantiate and use.
An interface on the other hand is merely a specification of methods that a class implements. It provides no other fields or behavioural implementation, just a list of methods that a class must implement. The main reason for this is to specify a common interface that objects can make use of.
I suppose the big difference is that of inheritance. With an abstract method, a sub-class ‘inherits’ the methods and implementations, it is an “IS-A” relationship. Whereas a class that ‘implements’ an interface doesn’t inherit methods, but implements them – it is more of a “HAS-A’ relationship than an “IS-A’ relationship. You can think of a class that implements an interface as a class that fulfills a role or adopts a selection of tasks.
Another distinction is that classes cannot inherit multiple abstract classes, while it can implement multiple interfaces.
Here’s another head scratcher … whats the difference between string’s compareTo() and equals()?
compareTo() returns an integer that represents the different between two strings. When strings are exactly the same length and sequence of characters it returns the difference of 0 (Zero).
equals() return a boolean that represents whether the string is equal to another object.
The equality operator ‘ == ‘ is used to compare if one reference points to the same object as another reference.