First, as a premise, inheritance has the following purposes. (Reference: http://equj65.net/tech/java8mixin/)
The actual inheritance patterns are the following two patterns.
Inheritance of specifications and implementation.kt
open class Person {
fun greet() { System.out.print("Hello") }
}
class Japanese: Person{ }
fun main(args: Array<String>) {
val taro = Japanese()
taro.greet()
}
Inherit only specifications.kt
interface Person {
fun greet()
}
class Japanese: Person{
override fun greet() { System.out.print("Hello") }
}
fun main(args: Array<String>) {
val taro = Japanese()
taro.greet()
}
As mentioned above, if you inherit only the specifications, you inherit the interface. This is because interface cannot contain an implementation. (It seems that you can have an implementation with _Java8, but I will not touch it here _)
It literally means inheriting from multiple classes.
There is a phenomenon called the diamond problem. Look at the code below.
diamondProblem (if implementation can be inherited multiple times).kt
interface Person {
fun greet()
}
open class Japanese: Person {
override fun greet() { System.out.print("Hello") }
}
class American: Person {
override fun greet() { System.out.print("Hello") }
}
//If such multiple inheritance is possible
class Half: Japanese(), American { }
fun main(args: Array<String>) {
val karl = Half()
karl.greet()
}
What kind of greeting does karl really make? This is actually a compilation error. This is because Java cannot have multiple parent classes.
Why can't I have multiple parent classes? Consider the case where the inherited parent class (Japanese, American) implements the method with the same name as in the above example. The compiler cannot resolve which method is called when the greet method is called from the inheriting class (Half).
Therefore, due to compiler reasons, Java cannot inherit multiple classes (! = Interface).
Inherit interface instead of inheriting implementation class. However, in this case, you have to write the implementation in the inherited class. Therefore, the implementation cannot be reused, and only the specifications can be inherited.
Inheritance of specifications seems to be similar to Duck Typing in Ruby. However, I think that inheritance of specifications is superior in the following points.
Implementation inheritance seems to be similar to Mix-in in Ruby. However, Mix-in is easier to use because it does not complicate the inheritance structure.
http://equj65.net/tech/java8mixin/ https://docs.oracle.com/javase/tutorial/java/IandI/multipleinheritance.html https://en.wikipedia.org/wiki/Multiple_inheritance https://en.wikipedia.org/wiki/Mixin
Recommended Posts