實例要求
- 定義一個整形數(shù)組類驮审,要求包含構(gòu)造方法,增加數(shù)據(jù)及輸出數(shù)據(jù)成員方法吉执,并利用書序?qū)崿F(xiàn)動態(tài)內(nèi)存分配疯淫。再次基礎(chǔ)上定義出以下子類:
- A、排序類 —— 實現(xiàn)排序
- B戳玫、反轉(zhuǎn)類 —— 實現(xiàn)數(shù)據(jù)反向存放
1熙掺、本實例主要采用的知識
集成的概念
2、具體內(nèi)容
class Array{ // 表示數(shù)組
private int temp[] ; // 整型數(shù)組
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{ // 反轉(zhuǎn)操作類
public ReverseArray(int len){
super(len) ;
}
public int[] getArray() {
int t[] = new int[super.getArray().length] ; // 開辟一個新的數(shù)組
int count = t.length - 1 ;
for(int x=0 ;x<t.length;x++){
t[count] = super.getArray()[x] ; // 數(shù)組反轉(zhuǎn)
count-- ;
}
return t ;
}
};
public class ArrayDemo{
public static void main(String args[]){
ReverseArray a = null ; // 聲明反轉(zhuǎn)類對象
a = new ReverseArray(5) ; // 開辟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[]){ // 輸出數(shù)組內(nèi)容
for(int x=0;x<i.length;x++){
System.out.print(i[x] + "咕宿、") ;
}
}
};
輸出結(jié)果:
true true true true true false 5币绩、 42、 2府阀、 21缆镣、 23、
排序類试浙,直接修改使用的子類即可:
輸出結(jié)果:
true true true true true false 2费就、5、 21川队、 23力细、 42、
3固额、總結(jié)
應(yīng)用了繼承的各個概念眠蚂,包括覆寫、子類對象的實例化過程斗躏,排序操作逝慧,可以發(fā)現(xiàn)使用繼承可以讓代碼得到重用。