blog podcast

Default in Java

I came across the keyword default in an interface in Java. Java used to be a very basic language, but in my view it has suffered severely from it’s own popularity. Because it’s so popular it has to keep it’s backward compatibility. At the same time it wants to add new cool features that are coming in other languages. Instead of JVM fans picking up new languages like Kotlin that have been designed to accomodate these features from the start there’s a big enough group of people that insist that these features need to be built into the Java language.

So what does the default keyword do? Well, it’s something you can mark a method with if you want to provide a default implementation for the method for classes that are inheriting the interface. Wait a minute you might say, isn’t this what we have abstract classes for? To provide some default functionality coupled with other methods that needs to be implemented? Yes, it kind of is. But in Java you can only extend one class, but you can implement many interfaces. In the end you get something like Traits in scala. A mixture between interfaces and real implementation.

Is this a good idea? If you ask me, no. This just means you add on the cognitive load of the java developer to solve some fringe problem. If people have this problem it might be that they should preferably use an alternative JVM language for that part of their problem.

Code of the Day

public interface Vehicle {
    
    String getBrand();
    
    String speedUp();
    
    String slowDown();
    
    default String turnAlarmOn() {
        return "Turning the vehicle alarm on.";
    }
    
    default String turnAlarmOff() {
        return "Turning the vehicle alarm off.";
    }
}

Example taken from Baeldung