吳裕雄--天生天然JAVA面向對象高級編程學習筆記:繼承的應用

class Array{        // 表示數組
    private int temp[] ;        // 整型數組
    private int foot ;    // 定義添加位置
    public Array(int len){ if(len>0){ this.temp = new int[len] ; }else{ this.temp = new int[1] ;    // 最少維持空間是1個
 } } public boolean add(int i){    // 增長元素
        if(this.foot<this.temp.length){    // 還有空間
            this.temp[foot] = i ;    // 增長元素
            this.foot ++ ;// 修改腳標
            return true ; }else{ return false ; } } public int[] getArray(){ return this.temp ; } }; class SortArray extends Array{    // 排序類
    public SortArray(int len){ super(len) ; } public int[] getArray(){    // 覆寫方法
        java.util.Arrays.sort(super.getArray()) ;    // 排序操做
        return super.getArray() ; } }; class ReverseArray extends Array{    // 反轉操做類
    public ReverseArray(int len){ super(len) ; } public int[] getArray() { int t[] = new int[super.getArray().length] ;    // 開闢一個新的數組
        int count = t.length - 1 ; for(int x=0 ;x<t.length;x++){ t[count] = super.getArray()[x] ;    // 數組反轉
            count-- ; } return t ; } }; public class ArrayDemo{ public static void main(String args[]){ // ReverseArray a = null ; // 聲明反轉類對象 // a = new ReverseArray(5) ; // 開闢5個空間大小
        SortArray a = null ; a = new SortArray(5) ; System.out.print(a.add(23) + "\t") ; System.out.print(a.add(21) + "\t") ; System.out.print(a.add(2) + "\t") ; System.out.print(a.add(42) + "\t") ; System.out.print(a.add(5) + "\t") ; System.out.print(a.add(6) + "\t") ; print(a.getArray()) ; } public static void print(int i[]){    // 輸出數組內容
        for(int x=0;x<i.length;x++){ System.out.print(i[x] + "、") ; } } };
相關文章
相關標籤/搜索