sayHello() 重複,類 C 需要實現自己的 sayHello()
Java代碼 interface A{ void showA(); default void sayHello(){ System.out.println("Hello, A!"); } } interface B{ void showB(); default void sayHello(){ System.out.println("Hello, B!"); } } class C implements A,B{ public void sayHello(){ System.out.println("Hello, C!"); } public static void main(String[] args){ C c = new C(); c.sayHello(); // Hello, C! } }
2、類方法的 優先順序 高於 介面方法
介面 A 和 類 B 中都定義了方法 sayHello() 的實現,
類 C 優先使用 類 B 的方法。
Java代碼 interface A{ void showA(); default void sayHello(){ System.out.println("Hello, A!"); } } class B{ public void sayHello(){ System.out.println("Hello, B!"); } } class C extends B implements A{ public static void main(String[] args){ C c = new C(); c.sayHello(); // Hello, B! } }
3、介面中不可以重寫 java.lang.Object 裡面的方法
Java代碼 interface A { // can't define a equals method in interface. default public boolean equals(){ } }
4、可以在介面中定義 static 方法
Java代碼 interface A{ void showA(); static void sayHello(){ System.out.println("Hello, A!"); } } class C { public static void main(String[] args){ A.sayHello(); // Hello, A! } }
二、Functional Programming VS. Object Oriented Programming
Functional Programming with Java 8 https://www.youtube.com/watch?v=LcfzV38YDu4
Java代碼 import java.util.Arrays; import java.util.List; import java.util.function.Consumer; class IConsumer implements Consumer<Integer>{ @Override public void accept(Integer t) { System.out.println(t); } } public class Java8ForEach { public static void main(String[] args) { List<Integer> list =Arrays.asList(1,2,3,5,6); // normal loop for(Integer i : list){ System.out.println(i); } // Java 8 forEach - normal Consumer<Integer> action = new IConsumer(); list.forEach(action); // Java 8 forEach - use lambda expressions. // see how we do it in one liner list.forEach(each -> System.out.println(each)); } }
五、Streaming API
Java collections got a new package java.util.Stream.
classes in this package provide a stream API.
And supports functional-style operations on streams of elements.
Stream API enables bulk operations like sequential or parallel map-readuce on Collections.
Java代碼 //Java 7 or earlier: public List listFilter(List<Integer> bigList){ List<Integer> filteredList = new ArrayList<>(); for (Integer p : bigList) { if (p > 40) { filteredList.add(p); } } return filteredList; }
Java代碼 //Java 8: public List listFilter(List<integer> bigList){ return bigList .stream() .filter(p -> p > 40) .collect(Collectors.toList()); }
-
So, if you know, in this world, it's an information age, we have a concept of "Big Data", "Haddoop", we have to process huge amount of data.
1) In stream we have two types of methods:
1. Intermediate method. Like: filter(), map()
lazy, it can't give result immediately until you call a terminate method.