Newer
Older
myNWP / src / PPAP.java
@Motoki Miura Motoki Miura on 22 Sep 2020 1 KB first commit for NWP exp
import java.util.ArrayList;

public class PPAP {

	public static void main(String[] args) {
		ArrayList<BaseObj> alist = new ArrayList<BaseObj>(); //可変長配列
		Pen pen = new Pen();
		Apple apple = null;
		alist.add(pen);
		alist.add(new Pineapple());
		alist.add(apple = new Apple());
		alist.add(pen);
		
		for(BaseObj bo: alist) {
			System.out.print(bo.getName()+"\t");
		}
		System.out.println("");
		for(BaseObj bo: alist) {
			System.out.print(bo.hashCode()+" "); // インスタンス/オブジェクト固有のID
		}
		System.out.println("");
		System.out.println("");
		
		// 通常の配列Version
		BaseObj[] ary = new BaseObj[4];
		ary[0] = pen;
		ary[1] = new Pineapple();
		ary[2] = apple;
		ary[3] = pen;
		for(BaseObj bo: ary) {
			System.out.print(bo.getName()+"\t");
		}
		System.out.println("");
		for(BaseObj bo: ary) {
			System.out.print(bo.hashCode()+" "); // インスタンス/オブジェクト固有のID
		}
		System.out.println("");
		System.out.println("");
		
		System.out.println("生成したオブジェクトの総数は?です"); // ?の部分を、数字におきかえてください
	}
}

class BaseObj {
	// インスタンス/オブジェクトが作られたときの「型」=「クラス名」を返す
	public String getName() {
		return getClass().getName();
	}
}
class Pen extends BaseObj { }
class Pineapple extends BaseObj { }
class Apple extends BaseObj { }