Here is an example code

public class Main<T> { public T value; private Main(T value){ this.value = value; } private T getT() { return value; } public static void main(String[] args) { Main<Integer> intobject = new Main<>(1); Integer valueinteger = intobject.getT(); System.out.println(valueinteger); } } 

Why is a constructor needed here? Why is it impossible without him?

    1 answer 1

    Why not? Possible without a constructor:

     public class Main<T> { public T value; private T getT() { return value; } public static void main(String[] args) { final Main<Integer> intObject = new Main<>(); intObject.value = 1; final Integer valueInteger = intObject.getT(); System.out.println(valueInteger); } } 

    PS In general, they usually do the opposite - private variable, and getter - public.