Hello! I read about generic, Optional class is given as an example.

 package chapt03; public class Optional <T> { private T value; public Optional() { } public Optional(T value) { this.value = value; } public T getValue() { return value; } public void setValue(T val) { value = val; } public String toString() { if (value == null) return null; return value.getClass().getName() + " " + value; } } 

Further in the main method there is such a code fragment:

 //параметризация по умолчанию - Object Optional ob3 = new Optional(); System.out.println(ob3.getValue()); 

Then there is a moment that I just can’t understand and ask for help in understanding it. Quote:

"Declaring a generic-type in the form of <T> , despite the possibility to use any type as a parameter, limits the scope of the class being developed. Variables of this type can only call methods of the Object class. Access to other methods restricts the compiler, preventing possible errors" .

But in main ob3 calls the class method Optional , which is not an Object method. What I do not understand?

  • Indicate the name of the book and the author, if not difficult. - Nofate
  • Pancakes "Java Industrial Programming" - Marty McFly
  • Just in the line Object Optional ob3 = new Optional (); Clearly a typo - Nofate
  • My fault. Object - part of previous comment - Marty McFly
  • one
    @Nofate, something is lately full of questions on Java generics ... - Qwertiy

1 answer 1

It's about using inside a generic class.

 public void setValue(T val) { value = val; // Вот тут на value можно вызывать только методы Object'а // Нельзя написать `value.length`, например, рассчитывая на то, // что кто-то сделает new Optional<String> } 

And the type of the Optional class itself is known and its methods can be called normally. As well as the methods associated with the generic type where it is installed:

 (new Optional<String>("abc")).getValue().length 
  • thank you so much! Very long tormented with this issue. - Marty McFly