1 /*
   2  * Copyright (c) 2013, Oracle and/or its affiliates. All rights reserved.
   3  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
   4  */
   5 
   6 
   7 /**
   8  * The sample illustrates rules to resolve conflicts between inheritance
   9  * candidates with <b>default methods</b>. There are two simple rules:
  10  * <ul>
  11  * <li>Class wins. If the superclass has a concrete or abstract declaration of
  12  * this method, it is preferred over all defaults.</li>
  13  * <li>Subtype wins. If an interface extends another interface, and both provide
  14  * a default, the more specific interface wins. </li>
  15  * </ul>
  16  */
  17 public class Inheritance {
  18 
  19     public interface Swimable {
  20 
  21         default void swim() {
  22             System.out.println("I can swim");
  23         }
  24     }
  25 
  26     /**
  27      * The abstract class that overrides {@link #swim} method
  28      */
  29     public abstract static class Fish implements Swimable {
  30 
  31         @Override
  32         public void swim() {
  33             System.out.println(this.getClass().getSimpleName() + " swims under water");
  34         }
  35     }
  36 
  37     /**
  38      * This class is used for illustration rule 1. See the source code of the
  39      * {@link #main} method
  40      * <pre>
  41      *      new Tuna().swim(); //"Tuna swims under water" output is suspected here
  42      * </pre>
  43      */
  44     public static class Tuna extends Fish implements Swimable {
  45     }
  46 
  47     /**
  48      * The interface that overrides {@link #swim} method (subtype of
  49      * {@link Swimable})
  50      */
  51     public interface Diveable extends Swimable {
  52 
  53         @Override
  54         default void swim() {
  55             System.out.println("I can swim on a water surface");
  56         }
  57 
  58         default void dive() {
  59             System.out.println("I can dive");
  60         }
  61     }
  62 
  63     /**
  64      * This class is used for illustration rule 2. See the source code of the
  65      * {@link #main} method
  66      * <pre>
  67      *      new Duck().swim(); //"I can swim on a water surface" output is suspected here
  68      * </pre>
  69      */
  70     public static class Duck implements Swimable, Diveable {
  71     }
  72 
  73     public static void main(String[] args) {
  74         // Illustrates the rule 1. The Fish.swim() implementation wins
  75         //"Tuna swims under water" output is suspected here
  76         new Tuna().swim();
  77 
  78         // Illustrates the rule 2. The Diveable.swim() implementation wins
  79         //"I can swim on a water surface" output is suspected here
  80         new Duck().swim();
  81     }
  82 }