Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Would it create issues if Number were to be implemented as an interface? Are there benefits?

Tags:

java

java-8

On a recent question I came accross the use of the Number abstract class.

Now since Java 8 is here, there are default methods, so Number could be an interface and written as:

public interface Number {
    public int intValue();

    public long longValue();

    public float floatValue();

    public double doubleValue();

    default public byte byteValue() {
        return (byte)intValue();
    }

    default public short shortValue() {
        return (short)intValue();
    }
}

Would old code using the Number abstract class still compile if this were the case? Are there any actual benefits in making Number an interface rather than an abstract class?

like image 972
skiwi Avatar asked Mar 23 '14 19:03

skiwi


1 Answers

Such kind of changes would certainly break the API immediately, and cause havoc into the world of Java programming. You just can't change a class (that too, the one which existed since the time Java is there), into an interface, because both have different meanings. And both are used in different ways.

For example, as soon as you make Number an interface, the immediate subclasses, say, Integer would break, as a class cannot extend from an interface, but has to implement it. But Integer class extends from Number.

You might argue that while changing Number, Java API designer could also change necessary subclasses in Java API accordingly. But they can't ignore the fact that, someone else might have their classes that extend from Number.

One more thing regarding the fact from which this question arose - an interface with default methods is not the same as an abstract class. This has been discussed quite a few times on SO itself, one of which is answered by you only.

like image 62
Rohit Jain Avatar answered Nov 10 '22 18:11

Rohit Jain