Home  >  Q&A  >  body text

Little doubts about java generic classes

There is a class defined as class Gift<T>{...},
When I create a new Gift object, such as Gift<Phone> ; myGift = new Gift<Phone>
What type is the myGift object? Is it Gift, Phone, or Object?
I read a paragraph on a blog that When instantiating an object, if you don’t specify a generic, the default is: Object, but if you don’t specify a generic, shouldn’t the default be GIft?

習慣沉默習慣沉默2685 days ago562

reply all(3)I'll reply

  • PHPz

    PHPz2017-05-17 10:05:19

    <T> This is just a generic declaration Gift<T> It means that you have the use of the generic type T in Gift. Java follows the principle of declaring first and then calling, so you need to declare the specific type of T before using T. The type of myGift has nothing to do with it. No matter what the type of T is, myGift is an object of a class called Gift.
    Hope to adopt it!

    reply
    0
  • 滿天的星座

    滿天的星座2017-05-17 10:05:19

    My personal understanding is that the restrictions of this type are restrictions on the parameters passed in, not the class itself

    reply
    0
  • 高洛峰

    高洛峰2017-05-17 10:05:19

    Gift, if you don’t specify a generic type, the default is: Object. That's for T, right? Java's generics need to determine the type during the compilation phase, and are not truly dynamic. So if the T type is not declared, T is assumed to be object by default

    reply
    0
  • Cancelreply