I am just trying myself to be comfortable with java api. But I am unable to do it. Not knowing the purpose of when to use abstract class.
Consider the java library collections
Collections
List Set
All 3 are interfaces but the major thing , though they have functions which are common that is add , addAll, contains,containsAll etc. List implements in its own and set implements in another way ( telling about duplication ). Set does not allow duplicates list allows duplicates.
So what I am trying to say is when ever there is no common features for sub-entity with super-entity we have to go for interface
To still more make it clear , if suppose we make Collection as abstract class we need some methods to be properly defined rather than just declared but the functionality of list and set is differnt ( no common definition to bothe) hence they just declared it as interface and made a force rule that both list and set should implement this.
But if there is some common functionality which both has then keep it as to be abstract class.
So to get an example from Java itself. Lets consider Number class which is made ABSTRACT. Lets see why it could not be done using interface now!!!
**public abstract class Number
extends Object
methods are**
byte byteValue()
Returns the value of the specified number as a byte.
abstract double doubleValue()
Returns the value of the specified number as a double.
abstract float floatValue()
Returns the value of the specified number as a float.
abstract int intValue()
Returns the value of the specified number as an int.
abstract long longValue()
Returns the value of the specified number as a long.
short shortValue()
Returns the value of the specified number as a short.
Now here the byteValue is a non-abstract method and other methods XXXValue are abstract. We will see Y???
byteValue()
// taken from Number class java doc api
public byte byteValue()
Returns the value of the specified number as a byte. This may involve rounding or truncation.
And this byteValue() method is being overriden by all the other classes like Integer,Double,Float etc.
Instead they can keep byteValue() also abstract !!! But they dint do it. Wish to know why they have done like this.
byteValue()is not overridden in all the Number subclasses. For example, it’s not in BigInteger, AtomicInteger, AtomicLong, BigDecimal. All those classes benefit from the default implementation in the Number class.