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!!!"); } }
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.
LikeLike
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.
LikeLike