SlideShare a Scribd company logo
1 of 48
Download to read offline
Interfaces,
evolved
Interfaces,
evolved
static
methods
default
methods
traits
functional
interfaces
Static Methods
Static Methods
//No different from static methods from classes
public interface StaticFoo {
static void foo() {
System.out.println("Static implementation of foo");
}
}
Default
Methods
Default
Methods
Previously, on Java 7
Default
Methods
signature
class
vision…
implem
contract…
Java 7 – Interfaces
Default
Methods
abstract
class
utility
class
static
methods
copy /
paste
Java 7 – Sharing Implementations
Default
Methods
Now, in Java 8…
Default
Methods
public interface Foo {
public default void foo() {
System.out.println("Default implementation of foo()");
}
}
Java 8 – Basic Syntax
Default
Methods
public interface Itf {
//No implementation; will be overridden
public void foo();
//Default implementation; will be overriden
public default void bar() {
System.out.println("Itf -> bar() [DEFAULT]");
}
//Default implementation; will not be overriden
public default void baz() {
System.out.println("Itf -> baz() [DEFAULT]");
}
}
Java 8 – Call &Overload
Default
Methods
public class Clazz implements Itf {
@Override
public void foo() {
System.out.println("Clazz -> foo()");
}
@Override
public void bar() {
System.out.println("Clazz -> bar()");
}
}
Java 8 – Call &Overload
Default
Methods
public class Test {
public static void main(String[] args) {
Clazz clz = new Clazz();
clz.foo();
clz.bar();
clz.baz();
}
}
Java 8 – Call &Overload
Clazz -> foo()
Clazz -> bar()
Itf -> baz() [DEFAULT]
Default
Methods
Diamond Inheritance
Default
Methods
public interface InterfaceA {
public default void foo() {System.out.println("A -> foo()");}
}
public interface InterfaceB {
public default void foo() {System.out.println("B -> foo()");}
}
public class Test implements InterfaceA, InterfaceB {
//Whoops
}
Diamond Inheritance
error: classTest inherits unrelated defaults for foo()
from types InterfaceA and InterfaceB
Default
Methods
//Solution 1 : the class method has the priority
public class Test implements InterfaceA, InterfaceB {
@Override
public void foo() {
System.out.println("Test -> foo()");
}
}
Diamond Inheritance
Default
Methods
//Solution 2 : we specify which method we want to call
public class Test implements InterfaceA, InterfaceB {
@Override
public void foo() {
InterfaceA.super.foo();
}
}
Diamond Inheritance
Default
Methods
Reflection & Proxies
Default
Methods
public static void main(String[] args) {
Object proxy = Proxy.newProxyInstance(
Test.class.getClassLoader(),
new Class[]{InterfaceA.class, InterfaceB.class},
(targetProxy, targetMethod, targetMethodArgs) -> {
System.out.println(targetMethod.toGenericString());
return null;
});
((InterfaceA) proxy).foo();
((InterfaceB) proxy).foo();
}
Reflection & Proxies
public default void defaultmethods.InterfaceA.foo()
public default void defaultmethods.InterfaceA.foo()
Default
Methods
public static void main(String[] args) {
Object proxy = Proxy.newProxyInstance(
Test.class.getClassLoader(),
new Class[]{InterfaceA.class, InterfaceB.class},
(targetProxy, targetMethod, targetMethodArgs) -> {
System.out.println(targetMethod.toGenericString());
return null;
});
((InterfaceB) proxy).foo();
((InterfaceA) proxy).foo();
}
Reflection & Proxies
public default void defaultmethods.InterfaceA.foo()
public default void defaultmethods.InterfaceA.foo()
Default
Methods
public static void main(String[] args) {
Object proxy = Proxy.newProxyInstance(
Test.class.getClassLoader(),
new Class[]{InterfaceB.class, InterfaceA.class},
(targetProxy, targetMethod, targetMethodArgs) -> {
System.out.println(targetMethod.toGenericString());
return null;
});
((InterfaceA) proxy).foo();
((InterfaceB) proxy).foo();
}
Reflection & Proxies
public default void defaultmethods.InterfaceB.foo()
public default void defaultmethods.InterfaceB.foo()
Default
Methods
When two or more interfaces of a proxy class contain a method
with the same name and parameter signature, the order of the
proxy class's interfaces becomes significant. When such a duplicate
method is invoked on a proxy instance, the Method object passed to
the invocation handler will not necessarily be the one whose declaring
class is assignable from the reference type of the interface that the
proxy's method was invoked through.This limitation exists because
the corresponding method implementation in the generated proxy
class cannot determine which interface it was invoked through.
Therefore, when a duplicate method is invoked on a proxy instance,
the Method object for the method in the foremost interface that
contains the method (either directly or inherited through a
superinterface) in the proxy class's list of interfaces is passed to the
invocation handler's invoke method, regardless of the reference type
through which the method invocation occurred.
java.lang.reflect.Proxy, 2014
Reflection & Proxies
Traits
functional interfaces
VS
Traits
Traits
From what I understood, a trait
encapsulates a single behavior.
Traits abstract
method
derived
methods
trait
…with their default
implementation
Traits
public interface Orderable<T> extends Comparable<T> {
//everything relies on the implementation of compareTo
public default boolean isAfter(T other) {
return compareTo(other) > 0;
}
public default boolean isBefore(T other) {
return compareTo(other) < 0;
}
public default boolean isSameAs(T other) {
return compareTo(other) == 0;
}
}
Traits
public class Person implements Orderable<Person> {
private final String name;
public Person(String name) {
this.name = name;
}
@Override
public int compareTo(Person other) {
return name.compareTo(other.name);
}
}
Traits
public class Test {
public static void main(String[] args) {
Person tony = new Person("Tony Stark");
Person bruce = new Person("Dr. Robert Bruce Banner");
println("Tony compareto Bruce : " + tony.compareTo(bruce));
println("Tony > Bruce : " + tony.isAfter(bruce));
println("Tony < Bruce : " + tony.isBefore(bruce));
println("Tony == Bruce : " + tony.isSameAs(bruce));
}
}
Tony compareTo Bruce : 16
Tony > Bruce : true
Tony < Bruce : false
Tony == Bruce : false
Functional
Interfaces
Functional
Interfaces
one abstract / many defaults…
Functional
Interfaces
@FunctionalInterface // optional
public interface Foo {
// 1 and only 1 abstract method
void foo();
// many defaults
default void bar() {…}
default void baz() {…}
…
}
one abstract / many defaults…
Functional
Interfaces
@FunctionalInterface
public interface Foo {
void foo();
void bar(); // whoops, one too many
}
one abstract / many defaults…
error: Foo is not a functional interface multiple non-overriding
abstract methods found in interface Foo
1 error
Functional
Interfaces
instance method
constructor
static method
lambda
…to pass them all
Functional
Interfaces
public class Name {
private String firstName;
private String lastName;
public Name(String firstName, String lastName) {
this.firstName = firstName;
this.lastName = lastName;
}
public String getFirstName() { return firstName; }
public String getLastName() { return lastName; }
}
Java 7
Functional
Interfaces
public class NameParser<T> {
public T parse(String name,Creator<T> creator) {
String[] tokens = name.split(" ");
String firstName = tokens[0];
String lastName = tokens[1];
return creator.create(firstName, lastName);
}
}
Java 7
Functional
Interfaces
public interface Creator<T> {
T create(String firstName, String lastName);
}
Java 7
Functional
Interfaces
public static void main(String[] args) {
NameParser<Name> parser = new NameParser();
Name res = parser.parse("Bruce Banner", new Creator<Name>() {
@Override
public Name create(String firstName, String lastName) {
return new Name(firstName, lastName);
}
});
}
Java 7
Functional
Interfaces
@FunctionalInterface
public interface Creator<T> {
T create(String firstName, String lastName);
}
Java 8
Functional
Interfaces Name res = parser.parse("Bruce Banner", Name::new);
Java 8
CONSTRUCTOR
Functional
Interfaces
public class Factory {
public static Name createName(String firstName, String lastName) {
return new Name(firstName, lastName);
}
}
Name res = parser.parse("Bruce Banner", Factory::createName);
Java 8
STATICMETHOD
Functional
Interfaces
public class Factory {
public Name createName(String firstName, String lastName) {
return new Name(firstName, lastName);
}
}
Factory factory = new Factory();
Name res = parser.parse("Bruce Banner", factory::createName);
Java 8
INSTANCEMETHOD
Functional
Interfaces Name res = parser.parse("Bruce Banner", (s1, s2) -> new Name(s1, s2));
Java 8
LAMBDAEXPRESSIONS
Functional
Interfaces
java.util.function
Functional
Interfaces
java.util.function
Biblio
Biblio
 CROISIER, Olivier. Java 8 : du neuf dans les interfaces !, 2014
http://thecodersbreakfast.net/index.php?post/2014/01/20/Java8-
du-neuf-dans-les-interfaces
 HORSTMANN, Cay S.. Java SE 8 for the Really Impatient. Addison-
Wesley, 2014
 SEIGNEURIN,Alexis. Java 8 – Interfaces fonctionnelles, 2014
http://blog.ippon.fr/2014/03/18/java-8-interfaces-fonctionnelles/

More Related Content

What's hot

Refactoring to Java 8 (Devoxx BE)
Refactoring to Java 8 (Devoxx BE)Refactoring to Java 8 (Devoxx BE)
Refactoring to Java 8 (Devoxx BE)Trisha Gee
 
Oracle Certified Associate (OCA) Java SE 8 Programmer II (1Z0-809) - Practice...
Oracle Certified Associate (OCA) Java SE 8 Programmer II (1Z0-809) - Practice...Oracle Certified Associate (OCA) Java SE 8 Programmer II (1Z0-809) - Practice...
Oracle Certified Associate (OCA) Java SE 8 Programmer II (1Z0-809) - Practice...Udayan Khattry
 
Interface
InterfaceInterface
Interfacevvpadhu
 
SoCal Code Camp 2015: An introduction to Java 8
SoCal Code Camp 2015: An introduction to Java 8SoCal Code Camp 2015: An introduction to Java 8
SoCal Code Camp 2015: An introduction to Java 8Chaitanya Ganoo
 
Operators
OperatorsOperators
Operatorsvvpadhu
 
Javaz. Functional design in Java 8.
Javaz. Functional design in Java 8.Javaz. Functional design in Java 8.
Javaz. Functional design in Java 8.Vadim Dubs
 
Антихрупкий TypeScript | Odessa Frontend Meetup #17
Антихрупкий TypeScript | Odessa Frontend Meetup #17Антихрупкий TypeScript | Odessa Frontend Meetup #17
Антихрупкий TypeScript | Odessa Frontend Meetup #17OdessaFrontend
 
Pj01 4-operators and control flow
Pj01 4-operators and control flowPj01 4-operators and control flow
Pj01 4-operators and control flowSasidharaRaoMarrapu
 
Pragmatic functional refactoring with java 8
Pragmatic functional refactoring with java 8Pragmatic functional refactoring with java 8
Pragmatic functional refactoring with java 8RichardWarburton
 
Advanced Debugging Using Java Bytecodes
Advanced Debugging Using Java BytecodesAdvanced Debugging Using Java Bytecodes
Advanced Debugging Using Java BytecodesGanesh Samarthyam
 
Java Programs
Java ProgramsJava Programs
Java Programsvvpadhu
 
The Ring programming language version 1.7 book - Part 35 of 196
The Ring programming language version 1.7 book - Part 35 of 196The Ring programming language version 1.7 book - Part 35 of 196
The Ring programming language version 1.7 book - Part 35 of 196Mahmoud Samir Fayed
 
On Parameterised Types and Java Generics
On Parameterised Types and Java GenericsOn Parameterised Types and Java Generics
On Parameterised Types and Java GenericsYann-Gaël Guéhéneuc
 

What's hot (20)

Refactoring to Java 8 (Devoxx BE)
Refactoring to Java 8 (Devoxx BE)Refactoring to Java 8 (Devoxx BE)
Refactoring to Java 8 (Devoxx BE)
 
JDK 8
JDK 8JDK 8
JDK 8
 
Oracle Certified Associate (OCA) Java SE 8 Programmer II (1Z0-809) - Practice...
Oracle Certified Associate (OCA) Java SE 8 Programmer II (1Z0-809) - Practice...Oracle Certified Associate (OCA) Java SE 8 Programmer II (1Z0-809) - Practice...
Oracle Certified Associate (OCA) Java SE 8 Programmer II (1Z0-809) - Practice...
 
final year project center in Coimbatore
final year project center in Coimbatorefinal year project center in Coimbatore
final year project center in Coimbatore
 
Interface
InterfaceInterface
Interface
 
SoCal Code Camp 2015: An introduction to Java 8
SoCal Code Camp 2015: An introduction to Java 8SoCal Code Camp 2015: An introduction to Java 8
SoCal Code Camp 2015: An introduction to Java 8
 
Operators
OperatorsOperators
Operators
 
Javaz. Functional design in Java 8.
Javaz. Functional design in Java 8.Javaz. Functional design in Java 8.
Javaz. Functional design in Java 8.
 
Антихрупкий TypeScript | Odessa Frontend Meetup #17
Антихрупкий TypeScript | Odessa Frontend Meetup #17Антихрупкий TypeScript | Odessa Frontend Meetup #17
Антихрупкий TypeScript | Odessa Frontend Meetup #17
 
Pj01 4-operators and control flow
Pj01 4-operators and control flowPj01 4-operators and control flow
Pj01 4-operators and control flow
 
Pragmatic functional refactoring with java 8
Pragmatic functional refactoring with java 8Pragmatic functional refactoring with java 8
Pragmatic functional refactoring with java 8
 
Clean code
Clean codeClean code
Clean code
 
Clean code
Clean codeClean code
Clean code
 
Advanced Debugging Using Java Bytecodes
Advanced Debugging Using Java BytecodesAdvanced Debugging Using Java Bytecodes
Advanced Debugging Using Java Bytecodes
 
Java Programs
Java ProgramsJava Programs
Java Programs
 
Sam wd programs
Sam wd programsSam wd programs
Sam wd programs
 
Clean code slide
Clean code slideClean code slide
Clean code slide
 
Java Generics
Java GenericsJava Generics
Java Generics
 
The Ring programming language version 1.7 book - Part 35 of 196
The Ring programming language version 1.7 book - Part 35 of 196The Ring programming language version 1.7 book - Part 35 of 196
The Ring programming language version 1.7 book - Part 35 of 196
 
On Parameterised Types and Java Generics
On Parameterised Types and Java GenericsOn Parameterised Types and Java Generics
On Parameterised Types and Java Generics
 

Viewers also liked

Java - Singleton Pattern
Java - Singleton PatternJava - Singleton Pattern
Java - Singleton PatternCharles Casadei
 
The Singleton Pattern Presentation
The Singleton Pattern PresentationThe Singleton Pattern Presentation
The Singleton Pattern PresentationJAINIK PATEL
 
Design Pattern - Singleton Pattern
Design Pattern - Singleton PatternDesign Pattern - Singleton Pattern
Design Pattern - Singleton PatternMudasir Qazi
 
Singleton Pattern (Sole Object with Global Access)
Singleton Pattern (Sole Object with Global Access)Singleton Pattern (Sole Object with Global Access)
Singleton Pattern (Sole Object with Global Access)Sameer Rathoud
 
Singleton design pattern
Singleton design patternSingleton design pattern
Singleton design pattern11prasoon
 
Design pattern (Abstract Factory & Singleton)
Design pattern (Abstract Factory & Singleton)Design pattern (Abstract Factory & Singleton)
Design pattern (Abstract Factory & Singleton)paramisoft
 

Viewers also liked (6)

Java - Singleton Pattern
Java - Singleton PatternJava - Singleton Pattern
Java - Singleton Pattern
 
The Singleton Pattern Presentation
The Singleton Pattern PresentationThe Singleton Pattern Presentation
The Singleton Pattern Presentation
 
Design Pattern - Singleton Pattern
Design Pattern - Singleton PatternDesign Pattern - Singleton Pattern
Design Pattern - Singleton Pattern
 
Singleton Pattern (Sole Object with Global Access)
Singleton Pattern (Sole Object with Global Access)Singleton Pattern (Sole Object with Global Access)
Singleton Pattern (Sole Object with Global Access)
 
Singleton design pattern
Singleton design patternSingleton design pattern
Singleton design pattern
 
Design pattern (Abstract Factory & Singleton)
Design pattern (Abstract Factory & Singleton)Design pattern (Abstract Factory & Singleton)
Design pattern (Abstract Factory & Singleton)
 

Similar to Java8 - Interfaces, evolved

Productive Programming in Java 8 - with Lambdas and Streams
Productive Programming in Java 8 - with Lambdas and Streams Productive Programming in Java 8 - with Lambdas and Streams
Productive Programming in Java 8 - with Lambdas and Streams Ganesh Samarthyam
 
Mirror, mirror on the wall: Building a new PHP reflection library (DPC 2016)
Mirror, mirror on the wall: Building a new PHP reflection library (DPC 2016)Mirror, mirror on the wall: Building a new PHP reflection library (DPC 2016)
Mirror, mirror on the wall: Building a new PHP reflection library (DPC 2016)James Titcumb
 
Lambda Chops - Recipes for Simpler, More Expressive Code
Lambda Chops - Recipes for Simpler, More Expressive CodeLambda Chops - Recipes for Simpler, More Expressive Code
Lambda Chops - Recipes for Simpler, More Expressive CodeIan Robertson
 
Thumbtack Expertise Days # 5 - Javaz
Thumbtack Expertise Days # 5 - JavazThumbtack Expertise Days # 5 - Javaz
Thumbtack Expertise Days # 5 - JavazAlexey Remnev
 
Java 8 - Lambdas and much more
Java 8 - Lambdas and much moreJava 8 - Lambdas and much more
Java 8 - Lambdas and much moreAlin Pandichi
 
Java 8 presentation
Java 8 presentationJava 8 presentation
Java 8 presentationVan Huong
 
FP in Java - Project Lambda and beyond
FP in Java - Project Lambda and beyondFP in Java - Project Lambda and beyond
FP in Java - Project Lambda and beyondMario Fusco
 
모던자바의 역습
모던자바의 역습모던자바의 역습
모던자바의 역습DoHyun Jung
 
The definitive guide to java agents
The definitive guide to java agentsThe definitive guide to java agents
The definitive guide to java agentsRafael Winterhalter
 
#5 (Remote Method Invocation)
#5 (Remote Method Invocation)#5 (Remote Method Invocation)
#5 (Remote Method Invocation)Ghadeer AlHasan
 
About java
About javaAbout java
About javaJay Xu
 
Esoft Metro Campus - Certificate in java basics
Esoft Metro Campus - Certificate in java basicsEsoft Metro Campus - Certificate in java basics
Esoft Metro Campus - Certificate in java basicsRasan Samarasinghe
 
JRuby and Invokedynamic - Japan JUG 2015
JRuby and Invokedynamic - Japan JUG 2015JRuby and Invokedynamic - Japan JUG 2015
JRuby and Invokedynamic - Japan JUG 2015Charles Nutter
 

Similar to Java8 - Interfaces, evolved (20)

Productive Programming in Java 8 - with Lambdas and Streams
Productive Programming in Java 8 - with Lambdas and Streams Productive Programming in Java 8 - with Lambdas and Streams
Productive Programming in Java 8 - with Lambdas and Streams
 
Mirror, mirror on the wall: Building a new PHP reflection library (DPC 2016)
Mirror, mirror on the wall: Building a new PHP reflection library (DPC 2016)Mirror, mirror on the wall: Building a new PHP reflection library (DPC 2016)
Mirror, mirror on the wall: Building a new PHP reflection library (DPC 2016)
 
Lambda Chops - Recipes for Simpler, More Expressive Code
Lambda Chops - Recipes for Simpler, More Expressive CodeLambda Chops - Recipes for Simpler, More Expressive Code
Lambda Chops - Recipes for Simpler, More Expressive Code
 
Java SE 8
Java SE 8Java SE 8
Java SE 8
 
Java 8 features
Java 8 featuresJava 8 features
Java 8 features
 
Java 8 new features
Java 8 new featuresJava 8 new features
Java 8 new features
 
Thumbtack Expertise Days # 5 - Javaz
Thumbtack Expertise Days # 5 - JavazThumbtack Expertise Days # 5 - Javaz
Thumbtack Expertise Days # 5 - Javaz
 
Java 8 Workshop
Java 8 WorkshopJava 8 Workshop
Java 8 Workshop
 
Java 8 - Lambdas and much more
Java 8 - Lambdas and much moreJava 8 - Lambdas and much more
Java 8 - Lambdas and much more
 
Java 8 presentation
Java 8 presentationJava 8 presentation
Java 8 presentation
 
Introduzione al TDD
Introduzione al TDDIntroduzione al TDD
Introduzione al TDD
 
FP in Java - Project Lambda and beyond
FP in Java - Project Lambda and beyondFP in Java - Project Lambda and beyond
FP in Java - Project Lambda and beyond
 
모던자바의 역습
모던자바의 역습모던자바의 역습
모던자바의 역습
 
Poly-paradigm Java
Poly-paradigm JavaPoly-paradigm Java
Poly-paradigm Java
 
The definitive guide to java agents
The definitive guide to java agentsThe definitive guide to java agents
The definitive guide to java agents
 
#5 (Remote Method Invocation)
#5 (Remote Method Invocation)#5 (Remote Method Invocation)
#5 (Remote Method Invocation)
 
About java
About javaAbout java
About java
 
Wien15 java8
Wien15 java8Wien15 java8
Wien15 java8
 
Esoft Metro Campus - Certificate in java basics
Esoft Metro Campus - Certificate in java basicsEsoft Metro Campus - Certificate in java basics
Esoft Metro Campus - Certificate in java basics
 
JRuby and Invokedynamic - Japan JUG 2015
JRuby and Invokedynamic - Japan JUG 2015JRuby and Invokedynamic - Japan JUG 2015
JRuby and Invokedynamic - Japan JUG 2015
 

Recently uploaded

20240415 [Container Plumbing Days] Usernetes Gen2 - Kubernetes in Rootless Do...
20240415 [Container Plumbing Days] Usernetes Gen2 - Kubernetes in Rootless Do...20240415 [Container Plumbing Days] Usernetes Gen2 - Kubernetes in Rootless Do...
20240415 [Container Plumbing Days] Usernetes Gen2 - Kubernetes in Rootless Do...Akihiro Suda
 
Powering Real-Time Decisions with Continuous Data Streams
Powering Real-Time Decisions with Continuous Data StreamsPowering Real-Time Decisions with Continuous Data Streams
Powering Real-Time Decisions with Continuous Data StreamsSafe Software
 
CRM Contender Series: HubSpot vs. Salesforce
CRM Contender Series: HubSpot vs. SalesforceCRM Contender Series: HubSpot vs. Salesforce
CRM Contender Series: HubSpot vs. SalesforceBrainSell Technologies
 
Salesforce Implementation Services PPT By ABSYZ
Salesforce Implementation Services PPT By ABSYZSalesforce Implementation Services PPT By ABSYZ
Salesforce Implementation Services PPT By ABSYZABSYZ Inc
 
SuccessFactors 1H 2024 Release - Sneak-Peek by Deloitte Germany
SuccessFactors 1H 2024 Release - Sneak-Peek by Deloitte GermanySuccessFactors 1H 2024 Release - Sneak-Peek by Deloitte Germany
SuccessFactors 1H 2024 Release - Sneak-Peek by Deloitte GermanyChristoph Pohl
 
Alfresco TTL#157 - Troubleshooting Made Easy: Deciphering Alfresco mTLS Confi...
Alfresco TTL#157 - Troubleshooting Made Easy: Deciphering Alfresco mTLS Confi...Alfresco TTL#157 - Troubleshooting Made Easy: Deciphering Alfresco mTLS Confi...
Alfresco TTL#157 - Troubleshooting Made Easy: Deciphering Alfresco mTLS Confi...Angel Borroy López
 
Maximizing Efficiency and Profitability with OnePlan’s Professional Service A...
Maximizing Efficiency and Profitability with OnePlan’s Professional Service A...Maximizing Efficiency and Profitability with OnePlan’s Professional Service A...
Maximizing Efficiency and Profitability with OnePlan’s Professional Service A...OnePlan Solutions
 
Sending Calendar Invites on SES and Calendarsnack.pdf
Sending Calendar Invites on SES and Calendarsnack.pdfSending Calendar Invites on SES and Calendarsnack.pdf
Sending Calendar Invites on SES and Calendarsnack.pdf31events.com
 
Ahmed Motair CV April 2024 (Senior SW Developer)
Ahmed Motair CV April 2024 (Senior SW Developer)Ahmed Motair CV April 2024 (Senior SW Developer)
Ahmed Motair CV April 2024 (Senior SW Developer)Ahmed Mater
 
A healthy diet for your Java application Devoxx France.pdf
A healthy diet for your Java application Devoxx France.pdfA healthy diet for your Java application Devoxx France.pdf
A healthy diet for your Java application Devoxx France.pdfMarharyta Nedzelska
 
Introduction Computer Science - Software Design.pdf
Introduction Computer Science - Software Design.pdfIntroduction Computer Science - Software Design.pdf
Introduction Computer Science - Software Design.pdfFerryKemperman
 
Implementing Zero Trust strategy with Azure
Implementing Zero Trust strategy with AzureImplementing Zero Trust strategy with Azure
Implementing Zero Trust strategy with AzureDinusha Kumarasiri
 
Cyber security and its impact on E commerce
Cyber security and its impact on E commerceCyber security and its impact on E commerce
Cyber security and its impact on E commercemanigoyal112
 
React Server Component in Next.js by Hanief Utama
React Server Component in Next.js by Hanief UtamaReact Server Component in Next.js by Hanief Utama
React Server Component in Next.js by Hanief UtamaHanief Utama
 
Unveiling Design Patterns: A Visual Guide with UML Diagrams
Unveiling Design Patterns: A Visual Guide with UML DiagramsUnveiling Design Patterns: A Visual Guide with UML Diagrams
Unveiling Design Patterns: A Visual Guide with UML DiagramsAhmed Mohamed
 
MYjobs Presentation Django-based project
MYjobs Presentation Django-based projectMYjobs Presentation Django-based project
MYjobs Presentation Django-based projectAnoyGreter
 
Innovate and Collaborate- Harnessing the Power of Open Source Software.pdf
Innovate and Collaborate- Harnessing the Power of Open Source Software.pdfInnovate and Collaborate- Harnessing the Power of Open Source Software.pdf
Innovate and Collaborate- Harnessing the Power of Open Source Software.pdfYashikaSharma391629
 
Xen Safety Embedded OSS Summit April 2024 v4.pdf
Xen Safety Embedded OSS Summit April 2024 v4.pdfXen Safety Embedded OSS Summit April 2024 v4.pdf
Xen Safety Embedded OSS Summit April 2024 v4.pdfStefano Stabellini
 
Balasore Best It Company|| Top 10 IT Company || Balasore Software company Odisha
Balasore Best It Company|| Top 10 IT Company || Balasore Software company OdishaBalasore Best It Company|| Top 10 IT Company || Balasore Software company Odisha
Balasore Best It Company|| Top 10 IT Company || Balasore Software company Odishasmiwainfosol
 

Recently uploaded (20)

20240415 [Container Plumbing Days] Usernetes Gen2 - Kubernetes in Rootless Do...
20240415 [Container Plumbing Days] Usernetes Gen2 - Kubernetes in Rootless Do...20240415 [Container Plumbing Days] Usernetes Gen2 - Kubernetes in Rootless Do...
20240415 [Container Plumbing Days] Usernetes Gen2 - Kubernetes in Rootless Do...
 
Powering Real-Time Decisions with Continuous Data Streams
Powering Real-Time Decisions with Continuous Data StreamsPowering Real-Time Decisions with Continuous Data Streams
Powering Real-Time Decisions with Continuous Data Streams
 
CRM Contender Series: HubSpot vs. Salesforce
CRM Contender Series: HubSpot vs. SalesforceCRM Contender Series: HubSpot vs. Salesforce
CRM Contender Series: HubSpot vs. Salesforce
 
Salesforce Implementation Services PPT By ABSYZ
Salesforce Implementation Services PPT By ABSYZSalesforce Implementation Services PPT By ABSYZ
Salesforce Implementation Services PPT By ABSYZ
 
SuccessFactors 1H 2024 Release - Sneak-Peek by Deloitte Germany
SuccessFactors 1H 2024 Release - Sneak-Peek by Deloitte GermanySuccessFactors 1H 2024 Release - Sneak-Peek by Deloitte Germany
SuccessFactors 1H 2024 Release - Sneak-Peek by Deloitte Germany
 
Advantages of Odoo ERP 17 for Your Business
Advantages of Odoo ERP 17 for Your BusinessAdvantages of Odoo ERP 17 for Your Business
Advantages of Odoo ERP 17 for Your Business
 
Alfresco TTL#157 - Troubleshooting Made Easy: Deciphering Alfresco mTLS Confi...
Alfresco TTL#157 - Troubleshooting Made Easy: Deciphering Alfresco mTLS Confi...Alfresco TTL#157 - Troubleshooting Made Easy: Deciphering Alfresco mTLS Confi...
Alfresco TTL#157 - Troubleshooting Made Easy: Deciphering Alfresco mTLS Confi...
 
Maximizing Efficiency and Profitability with OnePlan’s Professional Service A...
Maximizing Efficiency and Profitability with OnePlan’s Professional Service A...Maximizing Efficiency and Profitability with OnePlan’s Professional Service A...
Maximizing Efficiency and Profitability with OnePlan’s Professional Service A...
 
Sending Calendar Invites on SES and Calendarsnack.pdf
Sending Calendar Invites on SES and Calendarsnack.pdfSending Calendar Invites on SES and Calendarsnack.pdf
Sending Calendar Invites on SES and Calendarsnack.pdf
 
Ahmed Motair CV April 2024 (Senior SW Developer)
Ahmed Motair CV April 2024 (Senior SW Developer)Ahmed Motair CV April 2024 (Senior SW Developer)
Ahmed Motair CV April 2024 (Senior SW Developer)
 
A healthy diet for your Java application Devoxx France.pdf
A healthy diet for your Java application Devoxx France.pdfA healthy diet for your Java application Devoxx France.pdf
A healthy diet for your Java application Devoxx France.pdf
 
Introduction Computer Science - Software Design.pdf
Introduction Computer Science - Software Design.pdfIntroduction Computer Science - Software Design.pdf
Introduction Computer Science - Software Design.pdf
 
Implementing Zero Trust strategy with Azure
Implementing Zero Trust strategy with AzureImplementing Zero Trust strategy with Azure
Implementing Zero Trust strategy with Azure
 
Cyber security and its impact on E commerce
Cyber security and its impact on E commerceCyber security and its impact on E commerce
Cyber security and its impact on E commerce
 
React Server Component in Next.js by Hanief Utama
React Server Component in Next.js by Hanief UtamaReact Server Component in Next.js by Hanief Utama
React Server Component in Next.js by Hanief Utama
 
Unveiling Design Patterns: A Visual Guide with UML Diagrams
Unveiling Design Patterns: A Visual Guide with UML DiagramsUnveiling Design Patterns: A Visual Guide with UML Diagrams
Unveiling Design Patterns: A Visual Guide with UML Diagrams
 
MYjobs Presentation Django-based project
MYjobs Presentation Django-based projectMYjobs Presentation Django-based project
MYjobs Presentation Django-based project
 
Innovate and Collaborate- Harnessing the Power of Open Source Software.pdf
Innovate and Collaborate- Harnessing the Power of Open Source Software.pdfInnovate and Collaborate- Harnessing the Power of Open Source Software.pdf
Innovate and Collaborate- Harnessing the Power of Open Source Software.pdf
 
Xen Safety Embedded OSS Summit April 2024 v4.pdf
Xen Safety Embedded OSS Summit April 2024 v4.pdfXen Safety Embedded OSS Summit April 2024 v4.pdf
Xen Safety Embedded OSS Summit April 2024 v4.pdf
 
Balasore Best It Company|| Top 10 IT Company || Balasore Software company Odisha
Balasore Best It Company|| Top 10 IT Company || Balasore Software company OdishaBalasore Best It Company|| Top 10 IT Company || Balasore Software company Odisha
Balasore Best It Company|| Top 10 IT Company || Balasore Software company Odisha
 

Java8 - Interfaces, evolved

  • 4. Static Methods //No different from static methods from classes public interface StaticFoo { static void foo() { System.out.println("Static implementation of foo"); } }
  • 10. Default Methods public interface Foo { public default void foo() { System.out.println("Default implementation of foo()"); } } Java 8 – Basic Syntax
  • 11. Default Methods public interface Itf { //No implementation; will be overridden public void foo(); //Default implementation; will be overriden public default void bar() { System.out.println("Itf -> bar() [DEFAULT]"); } //Default implementation; will not be overriden public default void baz() { System.out.println("Itf -> baz() [DEFAULT]"); } } Java 8 – Call &Overload
  • 12. Default Methods public class Clazz implements Itf { @Override public void foo() { System.out.println("Clazz -> foo()"); } @Override public void bar() { System.out.println("Clazz -> bar()"); } } Java 8 – Call &Overload
  • 13. Default Methods public class Test { public static void main(String[] args) { Clazz clz = new Clazz(); clz.foo(); clz.bar(); clz.baz(); } } Java 8 – Call &Overload Clazz -> foo() Clazz -> bar() Itf -> baz() [DEFAULT]
  • 15. Default Methods public interface InterfaceA { public default void foo() {System.out.println("A -> foo()");} } public interface InterfaceB { public default void foo() {System.out.println("B -> foo()");} } public class Test implements InterfaceA, InterfaceB { //Whoops } Diamond Inheritance error: classTest inherits unrelated defaults for foo() from types InterfaceA and InterfaceB
  • 16. Default Methods //Solution 1 : the class method has the priority public class Test implements InterfaceA, InterfaceB { @Override public void foo() { System.out.println("Test -> foo()"); } } Diamond Inheritance
  • 17. Default Methods //Solution 2 : we specify which method we want to call public class Test implements InterfaceA, InterfaceB { @Override public void foo() { InterfaceA.super.foo(); } } Diamond Inheritance
  • 19. Default Methods public static void main(String[] args) { Object proxy = Proxy.newProxyInstance( Test.class.getClassLoader(), new Class[]{InterfaceA.class, InterfaceB.class}, (targetProxy, targetMethod, targetMethodArgs) -> { System.out.println(targetMethod.toGenericString()); return null; }); ((InterfaceA) proxy).foo(); ((InterfaceB) proxy).foo(); } Reflection & Proxies public default void defaultmethods.InterfaceA.foo() public default void defaultmethods.InterfaceA.foo()
  • 20. Default Methods public static void main(String[] args) { Object proxy = Proxy.newProxyInstance( Test.class.getClassLoader(), new Class[]{InterfaceA.class, InterfaceB.class}, (targetProxy, targetMethod, targetMethodArgs) -> { System.out.println(targetMethod.toGenericString()); return null; }); ((InterfaceB) proxy).foo(); ((InterfaceA) proxy).foo(); } Reflection & Proxies public default void defaultmethods.InterfaceA.foo() public default void defaultmethods.InterfaceA.foo()
  • 21. Default Methods public static void main(String[] args) { Object proxy = Proxy.newProxyInstance( Test.class.getClassLoader(), new Class[]{InterfaceB.class, InterfaceA.class}, (targetProxy, targetMethod, targetMethodArgs) -> { System.out.println(targetMethod.toGenericString()); return null; }); ((InterfaceA) proxy).foo(); ((InterfaceB) proxy).foo(); } Reflection & Proxies public default void defaultmethods.InterfaceB.foo() public default void defaultmethods.InterfaceB.foo()
  • 22. Default Methods When two or more interfaces of a proxy class contain a method with the same name and parameter signature, the order of the proxy class's interfaces becomes significant. When such a duplicate method is invoked on a proxy instance, the Method object passed to the invocation handler will not necessarily be the one whose declaring class is assignable from the reference type of the interface that the proxy's method was invoked through.This limitation exists because the corresponding method implementation in the generated proxy class cannot determine which interface it was invoked through. Therefore, when a duplicate method is invoked on a proxy instance, the Method object for the method in the foremost interface that contains the method (either directly or inherited through a superinterface) in the proxy class's list of interfaces is passed to the invocation handler's invoke method, regardless of the reference type through which the method invocation occurred. java.lang.reflect.Proxy, 2014 Reflection & Proxies
  • 25. Traits From what I understood, a trait encapsulates a single behavior.
  • 27. Traits public interface Orderable<T> extends Comparable<T> { //everything relies on the implementation of compareTo public default boolean isAfter(T other) { return compareTo(other) > 0; } public default boolean isBefore(T other) { return compareTo(other) < 0; } public default boolean isSameAs(T other) { return compareTo(other) == 0; } }
  • 28. Traits public class Person implements Orderable<Person> { private final String name; public Person(String name) { this.name = name; } @Override public int compareTo(Person other) { return name.compareTo(other.name); } }
  • 29. Traits public class Test { public static void main(String[] args) { Person tony = new Person("Tony Stark"); Person bruce = new Person("Dr. Robert Bruce Banner"); println("Tony compareto Bruce : " + tony.compareTo(bruce)); println("Tony > Bruce : " + tony.isAfter(bruce)); println("Tony < Bruce : " + tony.isBefore(bruce)); println("Tony == Bruce : " + tony.isSameAs(bruce)); } } Tony compareTo Bruce : 16 Tony > Bruce : true Tony < Bruce : false Tony == Bruce : false
  • 32. Functional Interfaces @FunctionalInterface // optional public interface Foo { // 1 and only 1 abstract method void foo(); // many defaults default void bar() {…} default void baz() {…} … } one abstract / many defaults…
  • 33. Functional Interfaces @FunctionalInterface public interface Foo { void foo(); void bar(); // whoops, one too many } one abstract / many defaults… error: Foo is not a functional interface multiple non-overriding abstract methods found in interface Foo 1 error
  • 35. Functional Interfaces public class Name { private String firstName; private String lastName; public Name(String firstName, String lastName) { this.firstName = firstName; this.lastName = lastName; } public String getFirstName() { return firstName; } public String getLastName() { return lastName; } } Java 7
  • 36. Functional Interfaces public class NameParser<T> { public T parse(String name,Creator<T> creator) { String[] tokens = name.split(" "); String firstName = tokens[0]; String lastName = tokens[1]; return creator.create(firstName, lastName); } } Java 7
  • 37. Functional Interfaces public interface Creator<T> { T create(String firstName, String lastName); } Java 7
  • 38. Functional Interfaces public static void main(String[] args) { NameParser<Name> parser = new NameParser(); Name res = parser.parse("Bruce Banner", new Creator<Name>() { @Override public Name create(String firstName, String lastName) { return new Name(firstName, lastName); } }); } Java 7
  • 39. Functional Interfaces @FunctionalInterface public interface Creator<T> { T create(String firstName, String lastName); } Java 8
  • 40. Functional Interfaces Name res = parser.parse("Bruce Banner", Name::new); Java 8 CONSTRUCTOR
  • 41. Functional Interfaces public class Factory { public static Name createName(String firstName, String lastName) { return new Name(firstName, lastName); } } Name res = parser.parse("Bruce Banner", Factory::createName); Java 8 STATICMETHOD
  • 42. Functional Interfaces public class Factory { public Name createName(String firstName, String lastName) { return new Name(firstName, lastName); } } Factory factory = new Factory(); Name res = parser.parse("Bruce Banner", factory::createName); Java 8 INSTANCEMETHOD
  • 43. Functional Interfaces Name res = parser.parse("Bruce Banner", (s1, s2) -> new Name(s1, s2)); Java 8 LAMBDAEXPRESSIONS
  • 46.
  • 48. Biblio  CROISIER, Olivier. Java 8 : du neuf dans les interfaces !, 2014 http://thecodersbreakfast.net/index.php?post/2014/01/20/Java8- du-neuf-dans-les-interfaces  HORSTMANN, Cay S.. Java SE 8 for the Really Impatient. Addison- Wesley, 2014  SEIGNEURIN,Alexis. Java 8 – Interfaces fonctionnelles, 2014 http://blog.ippon.fr/2014/03/18/java-8-interfaces-fonctionnelles/