Java 8 – Default and Static Method in Interface | Code Factory


Index Page : Link

Donate : Link

Medium Blog : Link

Applications : Link

Default Methods

  • Until 1.7 version onwards inside interface we can take only public abstract methods and public static final variables (every method present inside interface is always public and abstract whether we are declaring or not).
  • Every variable declared inside interface is always public static final whether we are declaring or not.
  • But from 1.8 version onwards in addition to these, we can declare default concrete methods also inside interface, which are also known as defender methods.
  • We can declare default method with the keyword “default” as follows
default void m1() {
	System.out.println("Default Method");
}
  • Interface default methods are by-default available to all implementation classes. Based on requirement implementation class can use these default methods directly or can override.

Example 1 :

package com.codeFactory.defaultAndStatic;

interface Interf {
	default void m1() {
		System.out.println("Default Method");
	}
}

public class Test implements Interf{
	public static void main(String... args) {
		Test t = new Test();
		t.m1();
	}
}

Output :

Default Method

Example 2 :

package com.codeFactory.defaultAndStatic;

interface Interf {
	default void m1() {
		System.out.println("Default Method");
	}
}

public class Test implements Interf{
	public void m1() {
		System.out.println("My own implementation");
	}
	public static void main(String... args) {
		Test t = new Test();
		t.m1();
	}
}

Output :

My own implementation
  • Default methods also known as defender methods or virtual extension methods.
  • The main advantage of default methods is without effecting implementation classes we can add new functionality to the interface (backward compatibility)

Note : We can’t override object class methods as default methods inside interface otherwise we get compile time error.

interface Interf {
	default int hashCode() {
		return 10;
	}
}

CE : default method hashCode in interface Interf overrides a member of java.lang.Object

Reason : Object class methods are by-default available to every Java class hence it’s not required to bring through default methods.

. . . . .

Default method vs multiple inheritance :

Two interfaces can contain default method with same signature then there may be a chance of ambiguity problem (diamond problem) to the implementation class. To overcome this problem compulsory we should override default method in the implementation class otherwise we get compiletime error.

package com.codeFactory.defaultAndStatic;

interface Left {
	default void m1() {
		System.out.println("Left.m1()");
	}
}

interface Right {
	default void m1() {
		System.out.println("Right.m1()");
	}
}

public class Test implements Left, Right {
	public void m1() {
		System.out.println("Test.m1()");
		Left.super.m1();
		Right.super.m1();
	}
	public static void main(String... args) {
		Test t = new Test();
		t.m1();
	}
}

Output :

Test.m1()
Left.m1()
Right.m1()

. . . . .

Difference between Interface with Default Methods and Abstarct Class :

Interface with Default MethodsAbstract Class
Inside interface every variable is always public static final and there is no chance of instance variablesInside abstract class there may be a chance of instance variables which Are required to the child class
Interface never talks about state of ObjectAbstract class can talk about state of Object
Inside interface we can’t declare ConstructorsInside abstract class we can declare Constructors
Inside interface we can’t declare instance and static blocksInside abstract class we can declare instance and static blocks
Functional interface with default methods can refer lambda expressionAbstract class can’t refer lambda expressions
Inside interface we can’t override Object class methods
e.g. equals(), hashCode()
Inside abstract class we can override Object class methods
e.g. equals(), hashCode()

Interface with default method != abstract class


Static methods inside interface

  • From 1.8 version onwards in addition to default methods we can write static methods also inside interface to define utility functions.
  • Interface static methods by-default not available to the implementation classes hence by using implementation class reference we can’t call interface static methods.
  • We should call interface static methods by using interface name.
package com.codeFactory.defaultAndStatic;

interface Interf {
	public static void sum(int a, int b) {
		System.out.println(a + b);
	}
}

public class Test implements Interf {
	public static void main(String... args) {
		sum(10, 20);            // X
		Test t = new Test();
		t.sum(10, 20);          // X
		Test.sum(10, 20);       // X
		Interf.sum(10, 20);     // ✓
	}
}

CE : cannot find symbol

  • As interface static methods by default not available to the implementation class, overriding concept is not applicable.
  • Based on our requirement we can define exactly same method in the implementation class, it’s valid but not overriding.

Interface static methods wrt (with respect to) overriding

Example 1 : This’s valid but not overriding

interface Interf {
	public static void m1() { }
}

public class Test implements Interf {
	public static void m1() { }
}

Example 2 : This’s valid but not overriding

interface Interf {
	public static void m1() { }
}

public class Test implements Interf {
	public void m1() { }
}

Example 3 : This’s valid but not overriding

interface Interf {
	public static void m1() { }
}

public class Test implements Interf {
	private static void m1() { }
}
  • From 1.8 version onwards we can write main() method inside interface and hence we can run interface directly from the command prompt.
interface Interf {
	public static void main(String... strings) {
		System.out.println("Main Method");
	}
}

Output :

Main Method

7 thoughts on “Java 8 – Default and Static Method in Interface | Code Factory”

  1. That is the right blog for anyone who desires to search out out about this topic. You notice a lot its virtually exhausting to argue with you (not that I truly would need…HaHa). You undoubtedly put a new spin on a topic thats been written about for years. Nice stuff, simply nice!

    Liked by 1 person

  2. I was very happy to find this internet-site.I wished to thanks to your time for this glorious read!! I definitely having fun with every little little bit of it and I have you bookmarked to take a look at new stuff you weblog post.

    Liked by 1 person

  3. Youre so cool! I dont suppose Ive learn anything like this before. So nice to search out any individual with some authentic ideas on this subject. realy thanks for starting this up. this website is something that’s needed on the web, someone with slightly originality. helpful job for bringing one thing new to the web!

    Liked by 1 person

Leave a Reply

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 )

Connecting to %s