类像“一台数据引擎”

来源:互联网 发布:域名必须实名认证吗 编辑:程序博客网 时间:2024/06/03 02:35

在java中,就是通过类这样的机制来完成封装性。在创建一个类时,你正在创建新的数据类型,1.定义属性。2定义操作数据的代码。进一步,方法定义了对该类数据相一致的控制接口。因此通过类的方法来使用类,而没必要担心他的实现细节或在类的内部数据实际上是如何管理的。

public class StackTest{public static void main(String[] args) {Stack mystack1=new Stack();Stack mystack2=new Stack();for (int i=0;i<10 ;++i ) {mystack1.push(i);}for (int i=10;i<20 ;++i ) {mystack2.push(i);}System.out.println("Stack in mystack1");for (int i=0;i<10 ;++i ) {System.out.println(mystack1.pop());}System.out.println("Stack in mystack2");for (int i=10;i<20 ; ++i) {System.out.println(mystack2.pop());}}}class Stack{int stck[] =new int[10];int tos;Stack(){tos=-1;}//Push item to the Stackvoid push(int item){if (tos==9) System.out.println("Stack is full.");elsestck[++tos]=item;}//Pop item from the Stackint pop(){if (tos<0){System.out.println("Stack is underflow");return 0;}elsereturn stck[tos--];}}


.

0 0