Interface has the list of all methods signatures, which specifies what the subclass can do, but not how.
If the subclass is not abstract, it must override all of these methods being specified in interface, otherwise it will not compile.
Question: Will the code below compile? If so, what happens when it runs?
1 2 3 4
publicstaticvoidmain(String[] args){ List61B<String> someList = new SLList<String>(); someList.addFirst("elk"); }
When it runs, an SLList is created and its address is stored in the someList variable. Then the string “elk” is inserted into the SLList referred to by addFirst.
Implementation Inheritance
Definition
Use the default keyword to specify a method that subclasses should inherit from an interface.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18
publicinterfaceList61B<Item> { publicvoidaddFirst(Item x); publicvoidaddLast(Item y); public Item getFirst(); public Item getLast(); public Item removeLast(); public Item get(int i); publicvoidinsert(Item x, int position); publicintsize(); // here comes the default method which have implementation defaultpublicvoidprint(){ for (int i = 0; i < size(); i += 1) { System.out.print(get(i) + " "); } System.out.println(); } }
In subclasses, default method from interface can also be override, when it been called, it will use its method instead of default.
Question: Which print method do you think will run when the code below executes?
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18
publicinterfaceSLList<Item> implements{ @Override publicvoidprint(){ for (Node p = sentinel.next; p != null; p = p.next) { System.out.print(p.item + " "); } System.out.println(); } }
The type specified at declaration is called static type (In example, the static type of someList is List61B).
The type specified at implementation (when using new) is called dynamic type (In example, the static type of someList is SLList).
In overriding, if the method has been specified by subclasses, the compiler will choose to record the method through dynamic type(which is subclass in the example).
However, in overloading, the compiler doesn’t have the dynamic type selection, so if the method has been implemented in the interface, it will be recorded even if there exists more specified method in subclass.