最近在学java中的对象,然后了解到通过java的对象的封装可以实现对其用户不需了解里面具体是怎么去实现的,这也是面向对象的思想;即一切由程序员实现,客户只需要知道怎么操作就可以了!!!不需了解具体实现;
就好像我们用java里面的库函数一样,设计和写库函数的是程序员,而我们编程用到里面的库函数的时候,我们并不了解它们是怎么去实现的我们此时就是客户:
下面给出一个例子就是模仿实现Stack的过程!
<span style="font-size:18px;">package stack; //此类为内部操作,用户看不到
public class StackofIntger {
private int[] elements;
private int size = 0;
public static final int DEFAULT_SIZE = 10;
StackofIntger(int firstsize) {
elements = new int[firstsize];
}
public boolean empty() {
return size == 0;
}
public int getTop() {
return elements[size - 1];
}
public void push(int value) {
if (size >= elements.length) { //空间不足重新申请空间
int [] temp = new int[elements.length * 2];
System.arraycopy(elements, 0, temp, 0, elements.length);
elements = temp;
}
elements[size++] = value;
}
public int pop() {
return elements[--size];
}
public int getSize() {
return size;
}
}
</span>
--------------------------------------------------------------------------------------------------------------------------------------------------------
-
<span style="font-size:18px;">package stack; //用户界面
public class TestOfStack {
public static void main(String[] args) {
StackofIntger s = new StackofIntger(20);
for (int i = 0; i < 10; i++) {
s.push(i);
}
while (!s.empty()) {
System.out.print(s.pop() + " ");
}
}
}
</span>
----------------------------------------------------------------------------------------------------------------------------------------------------------
用类来实现对对象的存储stack
<span style="font-size:18px;">package testClass;
import java.util.ArrayList;
public class Mystack {
private ArrayList<Object> List = new ArrayList<>(); //用ArrayList来进行自定义stack类用来存储对象
public boolean isEmpty() {
return List.isEmpty();
}
public int getSize() {
return List.size();
}
public Object peek() {
return List.get(List.size() - 1);
}
public Object pop(){
Object o = List.get(List.size() - 1);
List.remove(List.size() - 1);
return o;
}
public void push(Object o) {
List.add(o);
}
}
</span>