1、基本概念 html
Default methods enable you to add new functionality to the interfaces of your libraries and ensure binary compatibility with code written for older versions of those interfaces.
默認方法使您可以添加新的功能到你現有庫的接口中,並確保與採用老版本接口編寫的代碼的二進制兼容性。 java
什麼是默認方法(default methods)
即接口能夠有實現方法,並且不須要實現類去實現其方法。只需在方法名前面加個default關鍵字便可,這些方法默認是
爲何要有默認方法
爲何要有這個特性?首先,以前的接口是個雙刃劍,好處是面向抽象而不是面向具體編程,缺陷是,當須要修改接口時候,須要修改所有實現該接口的類,目前的java 8以前的集合框架沒有foreach方法,一般能想到的解決辦法是在JDK裏給相關的接口添加新的方法及實現。然而,對於已經發布的版本,是無法在給接口添加新方法的同時不影響已有的實現。因此引進的默認方法。他們的目的是爲了解決接口的修改與現有的實現不兼容的問題
2、 java 8抽象類與接口的區別
相同點:
1.都是抽象類型;
2.均可以有實現方法(java8才能夠)
3.均可以不須要實現類或者繼承者去實現全部方法
不一樣點
1.抽象類不能夠多重繼承,接口能夠(不管是多重類型繼承仍是多重行爲繼承);
2.抽象類和接口所反映出的設計理念不一樣。其實抽象類表示的是"is-a"關係,接口表示的是"like-a"關係;
3.接口中定義的變量默認是public static final 型,且必須給其初值,因此實現類中不能從新定義,也不能改變其值;抽象類中的變量默認是 friendly 型,其值能夠在子類中從新定義,也能夠從新賦值。
3、多重繼承的衝突說明
因爲同一個方法能夠從不一樣接口引入,天然而然的會有衝突的現象,默認方法判斷衝突的規則以下:
1.一個聲明在類裏面的方法優先於任何默認方法(classes always win)
2.不然,則會優先選取最具體的實現,好比下面的例子 B重寫了A的hello方法。
編程
4、如何擴展或實現帶有默認方法的接口? api
當前擴展一個默認方法的接口時,你能夠採用如下三種方式: oracle
1:讓擴展類繼承默認方法,根據不論是否存在默認方法 框架
2:從新聲明默認方法,使其變爲一個抽象方法(注意,擴展類的實現類必須實現此方法) ide
3:從新定義默認方法,覆蓋(override)父類的默認方法 ui
5、默認方法樣例代碼 this
import java.time.DateTimeException; import java.time.LocalDateTime; import java.time.ZoneId; import java.time.ZonedDateTime; public interface TimeClient { void setTime(int hour, int minute, int second); void setDate(int day, int month, int year); void setDateAndTime(int day, int month, int year, int hour, int minute, int second); LocalDateTime getLocalDateTime(); static ZoneId getZoneId(String zoneString) { try { return ZoneId.of(zoneString); } catch (DateTimeException e) { System.err.println("Invalid time zone: " + zoneString + "; using default time zone instead."); return ZoneId.systemDefault(); } } default ZonedDateTime getZonedDateTime(String zoneString) { return ZonedDateTime.of(getLocalDateTime(), getZoneId(zoneString)); } }
import java.time.LocalDate; import java.time.LocalDateTime; import java.time.LocalTime; import java.util.ArrayList; import java.util.Collections; import java.util.Comparator; import java.util.List; public class SimpleTimeClient implements TimeClient { private LocalDateTime dateAndTime; public SimpleTimeClient() { dateAndTime = LocalDateTime.now(); } public void setTime(int hour, int minute, int second) { LocalDate currentDate = LocalDate.from(dateAndTime); LocalTime timeToSet = LocalTime.of(hour, minute, second); dateAndTime = LocalDateTime.of(currentDate, timeToSet); } public void setDate(int year, int month, int day) { LocalDate dateToSet = LocalDate.of(year, month, day); LocalTime currentTime = LocalTime.from(dateAndTime); dateAndTime = LocalDateTime.of(dateToSet, currentTime); } public void setDateAndTime(int year, int month, int day, int hour, int minute, int second) { LocalDate dateToSet = LocalDate.of(year, month, day); LocalTime timeToSet = LocalTime.of(hour, minute, second); dateAndTime = LocalDateTime.of(dateToSet, timeToSet); } public LocalDateTime getLocalDateTime() { return dateAndTime; } public String toString() { return dateAndTime.toString(); } public static void main(String... args) { TimeClient client = new SimpleTimeClient(); // 顯示當前日期時間 System.out.println(client.toString()); // 設置日期 client.setTime(11, 12, 22); System.out.println(client); // 設置時間 client.setDate(2012, 11, 12); System.out.println(client); System.out.println("Time in Asia/Shanghai: " + client.getZonedDateTime("Asia/Shanghai").toString()); } }
6、整合默認方法、靜態方法到已經存在的接口 spa
默認方法使您可以添加新的功能到已經存在的接口,確保與採用老版本這些接口編寫的代碼的二進制兼容性。特別是,默認的方法使您可以在已經存在的接口中添加使用lambda表達式做爲參數的方法。下面的樣例代碼說明經過默認方法和靜態方法,Comparator 接口是如何提供豐富的功能的。
在java8中,Compartor接口提供了豐富的功能,提供了差很少近20個默認或靜態方法,在之前的版本中僅僅提供了compare(T o1, T o2)一個比較接口方法
下面的代碼是有關撲克牌遊戲中的洗牌,針對牌排序,打散,發牌的部分源代碼
package defaultmethods; //撲克牌接口類 public interface Card extends Comparable<Card> { public enum Suit { DIAMONDS (1, "Diamonds"), CLUBS (2, "Clubs" ), HEARTS (3, "Hearts" ), SPADES (4, "Spades" ); private final int value; private final String text; Suit(int value, String text) { this.value = value; this.text = text; } public int value() {return value;} public String text() {return text;} } public enum Rank { DEUCE (2 , "Two" ), THREE (3 , "Three"), FOUR (4 , "Four" ), FIVE (5 , "Five" ), SIX (6 , "Six" ), SEVEN (7 , "Seven"), EIGHT (8 , "Eight"), NINE (9 , "Nine" ), TEN (10, "Ten" ), JACK (11, "Jack" ), QUEEN (12, "Queen"), KING (13, "King" ), ACE (14, "Ace" ); private final int value; private final String text; Rank(int value, String text) { this.value = value; this.text = text; } public int value() {return value;} public String text() {return text;} } public Card.Suit getSuit(); public Card.Rank getRank(); }
package defaultmethods; import java.util.Comparator; import java.util.List; import java.util.Map; //牌桌接口類 public interface Deck { List<Card> getCards(); Deck deckFactory(); int size(); void addCard(Card card); void addCards(List<Card> cards); void addDeck(Deck deck); void shuffle(); void sort(); void sort(Comparator<Card> c); String deckToString(); Map<Integer, Deck> deal(int players, int numberOfCards) throws IllegalArgumentException; }
package defaultmethods; import java.util.Comparator; //先根據rank,再根據suit進行比較 public class SortByRankThenSuit implements Comparator<Card> { public int compare(Card firstCard, Card secondCard) { int compVal = firstCard.getRank().value() - secondCard.getRank().value(); if (compVal != 0) return compVal; else return firstCard.getSuit().value() - secondCard.getSuit().value(); } }
package defaultmethods; //撲克牌實現類 public class PlayingCard implements Card { private Card.Rank rank; private Card.Suit suit; public PlayingCard(Card.Rank rank, Card.Suit suit) { this.rank = rank; this.suit = suit; } public Card.Suit getSuit() { return suit; } public Card.Rank getRank() { return rank; } public boolean equals(Object obj) { if (obj instanceof Card) { if (((Card) obj).getRank() == this.rank && ((Card) obj).getSuit() == this.suit) { return true; } else { return false; } } else { return false; } } public int hashCode() { return ((suit.value() - 1) * 13) + rank.value(); } //實現比較接口 public int compareTo(Card o) { return this.hashCode() - o.hashCode(); } //重載toString public String toString() { return this.rank.text() + " of " + this.suit.text(); } public static void main(String... args) { new PlayingCard(Rank.ACE, Suit.DIAMONDS); new PlayingCard(Rank.KING, Suit.SPADES); } }
package defaultmethods; import java.util.ArrayList; import java.util.Collections; import java.util.Comparator; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.stream.Collectors; //牌桌實現類 public class StandardDeck implements Deck { //撲克牌列表 private List<Card> entireDeck; public StandardDeck(List<Card> existingList) { this.entireDeck = existingList; } public StandardDeck() { this.entireDeck = new ArrayList<>(); for (Card.Suit s : Card.Suit.values()) { for (Card.Rank r : Card.Rank.values()) { this.entireDeck.add(new PlayingCard(r, s)); } } } public Deck deckFactory() { return new StandardDeck(new ArrayList<Card>()); } public int size() { return entireDeck.size(); } public List<Card> getCards() { return entireDeck; } public void addCard(Card card) { entireDeck.add(card); } public void addCards(List<Card> cards) { entireDeck.addAll(cards); } public void addDeck(Deck deck) { List<Card> listToAdd = deck.getCards(); entireDeck.addAll(listToAdd); } public void sort() { Collections.sort(entireDeck); } public void sort(Comparator<Card> c) { Collections.sort(entireDeck, c); } public void shuffle() { Collections.shuffle(entireDeck); } //爲每位玩家分牌 public Map<Integer, Deck> deal(int players, int numberOfCards) throws IllegalArgumentException { int cardsDealt = players * numberOfCards; int sizeOfDeck = entireDeck.size(); if (cardsDealt > sizeOfDeck) { throw new IllegalArgumentException("Number of players (" + players + ") times number of cards to be dealt (" + numberOfCards + ") is greater than the number of cards in the deck (" + sizeOfDeck + ")."); } //把牌分紅幾份 int slices=players+1; if(cardsDealt == sizeOfDeck) slices=players; //根據玩家的個數,每一個玩家分到的撲克牌數進行分牌 Map<Integer, List<Card>> dealtDeck = entireDeck.stream().collect( Collectors.groupingBy(card -> { int cardIndex = entireDeck.indexOf(card); if (cardIndex >= cardsDealt) return (players + 1); else return (cardIndex % players) + 1; })); System.out.println(dealtDeck); // Convert Map<Integer, List<Card>> to Map<Integer, Deck> Map<Integer, Deck> mapToReturn = new HashMap<>(); for (int i = 1; i < (slices + 1); i++) { Deck currentDeck = deckFactory(); currentDeck.addCards(dealtDeck.get(i)); mapToReturn.put(i, currentDeck); } return mapToReturn; } public String deckToString() { return this.entireDeck.stream().map(Card::toString) .collect(Collectors.joining("\n")); } public String toString(){ return deckToString(); } public static void main(String... args) { System.out.println("Creating deck:"); StandardDeck myDeck = new StandardDeck(); myDeck.sort(); System.out.println("Sorted deck"); System.out.println(myDeck.deckToString()); myDeck.shuffle(); myDeck.sort(new SortByRankThenSuit()); System.out.println("Sorted by rank, then by suit"); System.out.println(myDeck.deckToString()); myDeck.shuffle(); myDeck.sort(Comparator.comparing(Card::getRank).thenComparing( Comparator.comparing(Card::getSuit))); System.out.println("Sorted by rank, then by suit " + "with static and default methods"); System.out.println(myDeck.deckToString()); myDeck.sort(Comparator.comparing(Card::getRank).reversed() .thenComparing(Comparator.comparing(Card::getSuit).reversed())); System.out.println("Sorted by rank reversed, then by suit " + "with static and default methods"); System.out.println(myDeck.deckToString()); myDeck.shuffle(); myDeck.sort( (firstCard, secondCard) -> firstCard.getRank().value() - secondCard.getRank().value() ); System.out.println(myDeck.deckToString()); myDeck.shuffle(); myDeck.sort(Comparator.comparing(Card::getRank)); System.out.println(myDeck.deckToString()); Map<Integer, Deck> map=myDeck.deal(4, 11); for(Map.Entry<Integer, Deck> item:map.entrySet()){ System.out.println(item.getKey()); System.out.println(item.getValue()); System.out.println("-------------------------------"); } } }
7、參考
http://docs.oracle.com/javase/8/docs/api/java/util/Comparator.html
http://docs.oracle.com/javase/tutorial/java/IandI/defaultmethods.html