Illuminatiiiiii
10/21/2018 - 8:30 PM

Generics Introduction

For episode 57 of the Java Tutorial:

//Class using Generics
class Booty<ParamType>{
    ParamType variable;

    public Booty(ParamType variable) {
        this.variable = variable;
    }

    public ParamType getVariable() {
        return variable;
    }

    public void setVariable(ParamType variable) {
        this.variable = variable;
    }
}
//Class not using generics
class Cat{
    Object object;

    public Cat(Object object) {
        this.object = object;
    }

    public Object getObject() {
        return object;
    }

    public void setObject(Object object) {
        this.object = object;
    }
}

public class Main {

    public static void main(String[] args) {


        Booty<String> booty1 = new Booty<String>("pickles are delicious"); //As you can see, we initialize the object as a String, and the thing in the parenthesis is the constructor
        System.out.println(booty1.getVariable());
        booty1.setVariable("pickles are bad");
        System.out.println(booty1.getVariable());

        //Here is us making another object, but as a Integer this time
        Booty<Integer> booty2 = new Booty<Integer>(45);
        System.out.println(booty2.getVariable());
        booty2.setVariable(10000);
        System.out.println(booty2.getVariable());

        //Example of auto un-boxing happening
        String one = booty1.getVariable();
        int two = booty2.getVariable(); //The right side returns a Integer Object, but the left side is an int primitive. The right side is auto un-boxed to an int.

        booty1 = booty2; //Cannot do this because booty1 and booty2 are two completely different object types
        
        //////////
        //Example of the problems for a non-generics class
        Cat kitty = new Cat(45);//45 is still autoboxed to it's counterpart object, Integer
        Cat kitty2 = new Cat("meow");

        //Now, if we want to set it to a variable, we have to cast manually every time. It can't be auto un-boxed
        int three = (Integer) kitty.getObject();
        String four = (String) kitty2.getObject(); //even kitty2 has to be manually unboxed to it's string literal counterpart

        //We can set the objects equal to each other because the class is of the type Object, so it doesnt know it's setting two incompatible objects to each other
        kitty = kitty2; //Kitty(Integer) is illegally set to Kitty2(String)
        int five = (Integer) kitty.getObject(); //Error happens at compile time because a Integer cannot be casted to a String!!!!
    }
}