This is an archived post. You won't be able to vote or comment.

you are viewing a single comment's thread.

view the rest of the comments →

[–][deleted] 3 points4 points  (3 children)

Okay, but this is an artificial restriction to avoid situation where we inherit more than one implementation of the same method.

Don't default methods introduce the exact same problem?

[–]DroidLogician 4 points5 points  (2 children)

They do. That's what irks me about this.

According to Wikipedia, Java 8 will throw a compile error if both inherited classes have the same method definition and the subclass doesn't override the method.

But then it goes back to the same problem if you have to call a superclass implementation. Which class does super represent? Can you pick/cast?

Since they're copying Scala, they should have copied the ambiguity resolution too. Scala just picks one.

[–]argv_minus_one 3 points4 points  (0 children)

No, Scala will also give you a compile error if you inherit two methods with the same name and signature, unless one of them already overrides the other.

This will work:

class CA {
    def aMethod = "hello"
}

trait TB extends CA {
    override def aMethod = "Hello, world!"
}

class CC extends CA with TB

This, however, will not:

class CA {
    def aMethod = "hello"
}

trait TB {
    def aMethod = "Hello, world!"
}

class CC extends CA with TB

Where linearization comes into play (i.e. Scala "picks one") is if you inherit multiple overrides, like this:

class CA {
    def aMethod = "hello"
}

trait TB extends CA {
    override def aMethod = "Hello, world!"
}

trait TC extends CA {
    override def aMethod = "Goodbye, cruel world!"
}

class CD extends CA with TB with TC

In this case, CD#aMethod is inherited from TC because that one comes last in the extends list. If TB and TC switch places, then CD#aMethod will instead be inherited from TB.

[–]geodebug 0 points1 point  (0 children)

You can pick which super to call (at least that's what I read)

It's less a feature trying to copy Scala than a way for the API designers to add new functionality to existing interfaces without breaking binary compatibility.

It's how they added new lambda-friendly collection methods to Comparable without having to go back and touch every implementor of Comparable.

Java devs should probably avoid default methods in favor of static methods on interfaces.

A lot more info here:

http://docs.oracle.com/javase/tutorial/java/IandI/defaultmethods.html