0

If I define the following class

public class SomeClass<T extends A> {..}

I of course can't define a variable this way - B is unrelated class.

SomeClass<B> instance = new SomeClass<B>();

But this works:

SomeClass instance = new SomeClass();

What am I missing?

Vic
  • 19,436
  • 10
  • 75
  • 91

3 Answers3

4

Generics in Java are optional.

If you use them, you have to use them "properly".

But if you don't use them at all, it will compile just fine (but you miss out on the type-safety features they provide, and should be getting a compile-time warning about it).

Thilo
  • 241,635
  • 91
  • 474
  • 626
1

Generics are compile time. At runtime, it is only SomeClass. Similar like we create non-generic list like :

List list = new ArrayList(); // you will get warning to use generics
Nandkumar Tekale
  • 14,991
  • 7
  • 52
  • 85
0

Generics will just help you and provide type safety, but just at compile time. After you have compiled your code correctly, the generic type will be erased and from the code perspective a List looks like a regular List without any generics.

One reason for that was backwards compatibility. Old 1.4 code which uses a List without generics will run as well as new code. Thus you can write a List without generics and any other class which uses generics. But of course you lose any type safety.

maerch
  • 1,985
  • 2
  • 16
  • 23