What will be the output of the following code?

package question;

class HasF {
    public void f() {
        System.out.println("HasF.f()");
    }
}

class Manipulators<T> {
    private T obj;
    public Manipulators(T x) {
        obj = x;
    }
    
    public void manipulation() {
        obj.f();
    }
}

public class Manipulation {
    public static void main(String[] args) {
        HasF hf = new HasF();
        Manipulators<HasF> manipul = new Manipulators<HasF>(hf);
        manipul.manipulation();
    }
}
Explanation
Generic types in Java are only working at the compilation level, the generated byte code does not contain any generic types. Type erasure replaces all type parameters in generic types with their bounds or Object if the type parameters are unbounded. Hence the class declaration class Manipulators<T> may be considered equivalent to class Manipulators<Object>. Since objects of type of Object don't have an f() method, the code will fail to compile.
In order to make it compile - we should set the boundaries: class Manipulators<T extends HasF>

Слідкуй за CodeGalaxy

Мобільний додаток Beta

Get it on Google Play
Зворотній Зв’язок
Продовжуйте вивчати
тести з Java
Cosmo
Зареєструйся Зараз
або Підпишись на майбутні тести