Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Generics in java just checking to make sure this is correct

I'm struggling with these (similar) problems on the bounded quantification of generics in Java:

  1. Write the header for a generic class named MyType. The class should have one type parameter. The type parameter’s upper bound should be the String class.

  2. Write the header for a generic class named MyType. The class should have one type parameter. The type parameter’s lower bound should be the Integer class.

    public class myType<T extends String>{}
    

    and

    public class myType<T extends Integer>{}
    

is this correct im really having a hard time grasping the concept of generics in java

like image 565
Chaz32621 Avatar asked May 23 '26 07:05

Chaz32621


1 Answers

You don't use extends to define both the upper bound and the lower bound.

According to Wikipedia's article on Generics in Java...

To specify the upper bound of a type wildcard, the extends keyword is used...

So to define the upper bound, use extends:

public class myType<T extends String>{}

Again, according to Wikipedia's article on Generics in Java...

To specify the lower bounding class of a type wildcard, the super keyword is used.


Addendum

I think whoever originally put this question together needs to sort a few things out.

  • Java does not have header files. Look up Header Files on Wikipedia, and it immediately states that Java does not use them:
    Some newer languages (such as Java) dispense with header files...
  • You cannot use a lower bound when defining a class - I believe it can only be done with a wildcard, which is not used when defining a class. The code public class MyClass<T super Integer> {} will give a syntax error: > expected

So all together, the question reeks of nonsense.

like image 75
Richard JP Le Guen Avatar answered May 24 '26 20:05

Richard JP Le Guen



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!