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

Default Methods

default void m1() {
System.out.println("Default Method");
}
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();
}
}
Default Method
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();
}
}
My own implementation
interface Interf {
default int hashCode() {
return 10;
}
}

Default method vs multiple inheritance :

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();
}
}
Test.m1()
Left.m1()
Right.m1()

Difference between Interface with Default Methods and Abstarct Class :

Static methods inside interface :

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); // ✓
}
}

Interface static methods wrt (with respect to) overriding :

interface Interf {
public static void m1() { }
}
public class Test implements Interf {
public static void m1() { }
}
interface Interf {
public static void m1() { }
}
public class Test implements Interf {
public void m1() { }
}
interface Interf {
public static void m1() { }
}
public class Test implements Interf {
private static void m1() { }
}
interface Interf {
public static void main(String... strings) {
System.out.println("Main Method");
}
}
Main Method

--

--

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store