Sobes.tech
Junior — Middle

Explain how the use of abstract classes differs in Java and Kotlin.

sobes.tech AI

Answer from AI

In Java and Kotlin, abstract classes are used to create base classes that cannot be instantiated directly but can be inherited.

Differences:

  • In Kotlin, all classes are final by default, so to create an abstract class, you need to explicitly use the abstract keyword. In Java, classes are not final by default, but abstract is also used for abstract classes.

  • In Kotlin, abstract classes can contain both abstract and concrete methods, just like in Java.

  • Kotlin has interfaces with default implementations, which reduces the need for abstract classes in some cases.

  • Kotlin supports multiple inheritance of interfaces, but not classes, similar to Java.

Example of an abstract class in Kotlin:

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

class Dog : Animal() {
    override fun makeSound() {
        println("Woof")
    }
}

Similarly in Java:

abstract class Animal {
    abstract void makeSound();
    void sleep() {
        System.out.println("Sleeping");
    }
}

class Dog extends Animal {
    @Override
    void makeSound() {
        System.out.println("Woof");
    }
}
Explain how the use of abstract classes differs in… - sobes.tech