interface Animal{ void breathe(); void run(); void eat(); } class Dog implements Animal{ public void breathe(){ System.out.println("I'm breathing"); } void eat(){ System.out.println("I'm eating"); } } public class Test{ public static void main(String[] args){ Dog dog = new Dog(); dog.breathe(); dog.eat(); } }
不能經過編譯,Dog類繼承Animal,Dog類必須實現接口的抽象全部方法,應該添加未實現的方法。java
interface Animal{ void breathe(); void run(); void eat(); } class Dog implements Animal{ public void breathe(){ System.out.println("I'm breathing"); } public void eat(){ System.out.println("I'm eating"); } public void run() { System.out.println("I'm running"); } } public class Test{ public static void main(String[] args){ Dog dog = new Dog(); dog.breathe(); dog.eat(); dog.run(); } }
運行結果爲:git
I'm breathing I'm eating I'm running
import java.util.Arrays; public class Test{ public static void main(String[] args){ String[] fruits = {"peach","banana","orange","apple"}; Arrays.sort(fruits); for(int i = 0;i < fruits.length;i++) { System.out.println(fruits[i]); } } }
運行結果爲:編程
apple banana orange peach
按降序排列:設計模式
import java.util.Arrays; import java.util.Comparator; public class Test { public static void main(String[] args) { String[] fruits = { "peach", "banana", "orange", "apple" }; Arrays.sort(fruits, new Comparator<String>() { public int compare(String o1, String o2) { char a = o1.charAt(0); char b = o2.charAt(0); if(o1.equals(o2)){ return 0; }else if(a>b){ return -1; }else{ return 1; } } }); for (int i = 0; i < fruits.length; i++) { System.out.println(fruits[i]); } } }
運行結果爲:數組
peach orange banana apple
String類繼承了comparable接口,用compareTo方法比較,Arrays只提供基本數據類型數組排序,其餘的都從屬於Arrays.sort(Object[]),對象數組的排序。app
public final class String implements java.io.Serializable,Comparable<String>, CharSequence { public int compareTo(String anotherString) { int len1 = value.length; int len2 = anotherString.value.length; int lim = Math.min(len1, len2); char v1[] = value; char v2[] = anotherString.value; int k = 0; while (k < lim) { char c1 = v1[k]; char c2 = v2[k]; if (c1 != c2) { return c1 - c2; } k++; } return len1 - len2; }
}學習
程序設計思路:定義一個MusicBox接口,具備play()方法,定義兩個音樂盒類,分別實現MusicBox接口,定義一個工廠類MusicBoxFactory,實現對PianoBox和Violinbox對象的建立。ui
http://git.oschina.net/hebau_cs15/Java-CS02lc/tree/master
.net