Sobes.tech
Junior — Middle

Milline on erinevus Java ja Kotlin abstraktse meetodi vahel?

sobes.tech AI

Vastus AI-lt

In Java, an abstract method is declared in an abstract class and has no implementation. The class containing an abstract method must be declared as abstract, and all subclasses are obliged to implement this method if they are not abstract.

In Kotlin, abstract methods are also declared in abstract classes, but there is an important difference: in Kotlin, methods with implementation can be declared in abstract classes (open or abstract), and interfaces can contain methods with implementation (default methods). An abstract method in Kotlin is a method without a body, which must be overridden in subclasses.

Example in Kotlin:

abstract class Animal {
    abstract fun makeSound()
    fun sleep() {
        println("Sleeping")
    }
}

Here, makeSound is an abstract method, sleep is a method with implementation.

Therefore, the difference is that Kotlin is more flexible in defining methods with implementation in abstract classes and interfaces, while Java requires that abstract methods have no implementation and are located in abstract classes or interfaces with default methods.