0
public class GenericHolder<T> {
    private T object;
    
    public T get(){
        return object;
    }
   
    public void set(T obj){
        this.object = obj;
    }


    public static void main(String args[]){
         GenericHolder holder = new GenericHolder<Integer>();
         holder.set("10"); 
        
    }


}

I understand that holder (non parameterized) can reference parameterized type (with Integer)... But why Java allows to set String, when it is expected Integer...

Questw
  • 43
  • 4
  • Yes, this helped me.. But actually I want to know what is going on in memory.. How we can save String on a place where is expected Integer.. Or maybe we save it on the other position.. Is it the same Object (parameterized with Integer).. – Questw Aug 15 '20 at 10:12
  • 2
    "where is expected Integer" it's not expecting an Integer. It's just an Object. The fact it "should be" an Integer is supposed to be enforced by compile-time type checking and inserted casts; but these can't be enforced because of the raw type of the variable. – Andy Turner Aug 15 '20 at 10:15
  • 1
    Due to [type erasure](https://docs.oracle.com/javase/tutorial/java/generics/erasure.html), all generic parameters are replaced with their bound at compile-time, thus, at runtime, only the upper bounds are left. Not the actual types. If no bound is specified, we are left with `Object` as implicit upper bound. – Turing85 Aug 15 '20 at 10:16
  • Thank you guys very much.. Type erasure was the part that I did not know.. Thanks. – Questw Aug 15 '20 at 10:20

0 Answers0