/* * This file contains several generefied classes and simple demonstration of the * usage of those classes. While examing the code, it is important to remember * that -- in Java -- it is the Job of the COMPILER to check and enforce type * saftey. At runtime, it is assumed that the compiler (and hence, the programmer) * has already resolved any potential "type saftey" issues. */ package Generics; /** * @author Adam J. Conover */ public class GenericClass { /** * This class is just used to test/demonstrate the classes below. * @param args the command line arguments */ public static void main(String[] args) { Fuji f1 = new Fuji(335); Orange f2 = new Orange(275); Sunkist f3 = new Sunkist(); MySimpleContainer appleContainer = new MySimpleContainer(f1); MyComparableContainer appleComparable = new MyComparableContainer(f1); MyComplicatedContainer orangeContainer = new MyComplicatedContainer(f2, f3); } } /** * A generified class is just like any other class, but includes the ability to use * types that are determined by the user of the class instead of types specified by * the class designer. * * @author Adam J. Conover * @param T is substituted for the class specified by the user of the class. */ class MySimpleContainer { private T data; public MySimpleContainer(T data) { this.setData(data); } /** * @return the data */ public T getData() { return this.data; } /** * @param data the data to set */ public void setData(T data) { this.data = data; } } /** * This is a slightly more elaborate example where T is a type which extends another * type which is also generified. However, simple substitution can be used to * figure out what is going on. * * @author Adam J. Conover * @param The user specified type which will replace all occurrences of T. * T must be comparable to itself or any of it's super types. */ class MyComparableContainer> implements Comparable { private T data; public MyComparableContainer(T data) { this.data = data; } /** * @return the data */ public T getData() { return this.data; } /** * @param data the data to set */ public void setData(T data) { this.data = data; } @Override public int compareTo(T other) { return this.data.compareTo(other); } } /** * An even more elaborate class declaration which utilizes multiple generic types * and inheritance. * * @author Adam J. Conover * @param The user specified type which will replace all occurrences of T. * T must be comparable to itself or any of it's super types. * @param The user specified type, which extends T, and will replace all * occurrences of U. */ class MyComplicatedContainer, U extends T> extends MyComparableContainer { private U localData; public MyComplicatedContainer(T parm1, U parm2) { super(parm1); this.localData = parm2; } /** * @return the localData */ public U getLocalData() { return localData; } /** * @param localData the localData to set */ public void setLocalData(U localData) { this.localData = localData; } }