Junior — Middle
How do inheritance mechanisms differ in Java and Kotlin?
sobes.tech AI
Answer from AI
In Java, inheritance is implemented using the extends keyword for classes and implements for interfaces. Classes support single inheritance (one parent class), but can implement multiple interfaces. All methods in Java are non-virtual by default, but parent methods can be overridden.
In Kotlin, inheritance is more flexible:
- Classes are
finalby default (cannot be inherited), to allow inheritance, a class must be declared asopen. - Inheritance is specified with
:and the parent constructor is called immediately after the class name. - Kotlin supports multiple inheritance of interfaces and allows interfaces to contain method implementations.
- Methods and properties are
finalby default; to override,openmust be used in the parent andoverridein the child.
Example:
Java:
class Animal {
void sound() { System.out.println("Some sound"); }
}
class Dog extends Animal {
@Override
void sound() { System.out.println("Bark"); }
}
Kotlin:
open class Animal {
open fun sound() { println("Some sound") }
}
class Dog : Animal() {
override fun sound() { println("Bark") }
}
Thus, Kotlin makes inheritance more strict and explicit, which enhances code safety and reduces errors.