2018年11月6日 星期二

java 犯行

/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */
package test_4;

import static java.lang.System.out;

class T_4_A {

    String name = "A";

    public T_4_A() {

    }

    public T_4_A(String name) {
        this.name = name;
    }

    public String getName() {
        return name;
    }
}

class T_4_B extends T_4_A {

    public String name = "...B";

    public T_4_B() {
        super("B");
    }

    public T_4_B(String name) {
        super(name);
    }
}

class T_4_C extends T_4_B {

    public String name = "...C";

    public T_4_C() {
        super("C");
    }

    public T_4_C(String name) {
        super(name);
    }
}
//==============================================================================

class T_4_Bag<T> {

    public int set_index = 0;
    public int get_index = 0;
    public T[] content;

    T_4_Bag() {
        this.content = (T[]) (new Object[10]);
    }

    void add(T t) {
        if (set_index == (content.length - 1)) {
            throw new Error("bag full");
        }
        content[set_index++] = t;
    }

    Boolean next() {
        if (get_index < set_index && content[get_index] != null) {
            return true;
        }
        return false;
    }

    T result() {
        return content[get_index++];
    }
}
//==============================================================================

/**
 *
 * @author xman
 */
public class T_4 {

    public static void test_1() {
        T_4_Bag<T_4_A> bag = new T_4_Bag<>();

        bag.add(new T_4_A());

        T_4_Bag<? super T_4_B> bag_1 = bag;

        // bag_1.add(new T_4_A()); // error
        bag_1.add(new T_4_B());

        while (bag_1.next()) {
            T_4_A o = (T_4_A) (bag_1.result());
            out.printf("(%s)=>(%s)\n", o.name, o.getName());
        }
    }
    //--------------------------------------
    public static void test_2() {
        T_4_Bag<T_4_B> bag = new T_4_Bag<>();

        bag.add(new T_4_B());

        T_4_Bag<? super T_4_B> bag_1 = bag;
      
        bag_1.add(new T_4_B());
        bag_1.add(new T_4_C());

        while (bag_1.next()) {
            T_4_B o = (T_4_B) (bag_1.result());
            out.printf("(%s)=>(%s)\n", o.name, o.getName());
        }
    }
    //--------------------------------------
    /**
     * @param args the command line arguments
     */
    public static void main(String[] args) {
        // test_1();
        test_2();
    }

}