[Java 教學範例拷貝]- Object 類別
剛才找資料時發現一個的Java 教學網站,趕快發揮(C/P)的長才將它備份來,有需要的同好,歡迎來(C/P)一下^^。
拷貝來源:
http://openhome.cc/Gossip/JavaGossip-V1/
http://openhome.cc/Gossip/JavaGossip-V1/ObjectClass.htm
public class Foo1 { private String name; public Foo1(String name) { this.name = name; } public void showName() { System.out.println("foo1 name: " + name); } // 重新定義toString() public String toString() { return "foo1 name: " + name; } } public class Foo2 { private String name; public Foo2(String name) { this.name = name; } public void showName() { System.out.println("foo2 name: " + name); } // 重新定義toString() public String toString() { return "foo2 name: " + name; } } public class SimpleCollection { private Object[] objArr; private int index = 0; public SimpleCollection() { objArr = new Object[10]; // 預設10個物件空間 } public SimpleCollection(int capacity) { objArr = new Object[capacity]; } public void add(Object o) { objArr[index] = o; index++; } public int getLength() { return index; } public Object get(int i) { return objArr[i]; } } public class Test { public static void main(String[] args) { SimpleCollection objs = new SimpleCollection(); objs.add(new Foo1("f1 number 1")); objs.add(new Foo2("f2 number 1")); Foo1 f1 = (Foo1) objs.get(0); f1.showName(); Foo2 f2 = (Foo2) objs.get(1); f2.showName(); System.out.println(); System.out.println("f1.toString(): " + f1.toString()); System.out.println("f2.toString(): " + f2.toString()); } }
|
沒有留言:
張貼留言