Java 8 | Default methods in interface

Every developer in office is instructed to write no-nonsense code. That’s a protocol.

So when there is no exception, why should every developer create their own creative ways to code. Every one should follow a consistent methodology. Let that manager of your’s define the PMDs for you. I know you will gonna hate it. But then…

It makes sense to have some non abstract methods in an interface. This may be conveniently called default implementation.

Java 8 let you do this. Now you can define a default implementation, which is available to all implementing classes.

Below is a sample.

Interface

package com.bitbyte;

public interface Developer {
	
	public void writeReadableCode();
	
	default void thinkSimple(){
		System.out.println("At bitbyte, Developers think Simple");
	}

}

Implementing class

package com.bitbyte;

public class JavaDeveloper implements Developer {

	@Override
	public void writeReadableCode() {
		System.out.println("Please write Simple and readable code");
	}
}

Client Class

package com.bitbyte;

public class Client {

	public static void main(String args[]) {

		JavaDeveloper coolDeveloper = new JavaDeveloper();
		
		// abstract method call
		coolDeveloper.writeReadableCode();
		// Non abstract method call
		coolDeveloper.thinkSimple();
	}
}

Since you always have a jackAss in team, who still want his own implementation. He can do so.


package com.bitbyte;

public class CoolDeveloper implements Developer {

	@Override
	public void writeReadableCode() {
		System.out.println("Please write Simple and readable code");
	}
	
	@Override
	public void thinkSimple() {
		
		System.out.println("I am cool myself. I know what i am doing!!!");
		
	}
}

2 thoughts on “Java 8 | Default methods in interface

  1. I am sorry mate but what’s the actual purpose of this concept’s existence? When you said ‘It makes sense to have some non abstract methods in an interface’, I didn’t get your point in this line. what sense does it make to have a default method in an Interface. If you could differentiate and share a practical example then I will really appreciate it.

    Like

    • it makes sense, since not all implementing classes are forced to write boilerplate code, till they really want to have a different implementation than default one in interface.

      Like

What do you think?

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s