0
public class A<B> {
    public func() {
        B b = new B();
    }
}

I get this error hint from Netbeans:

unexpected type
  required: class
  found:    type parameter B
  where Bis a type-variable:
    B extends Object declared in class A

How can I new a object of class B?

2

4 Answers 4

2

B in A<B> is just a type parameter. You cannot create an instantiate a parameter. You can only create an instance of actual type.

But you can declare the method to take that instance as an argument public func(B b).

I recommend you to read the tutorial on generics.

Sign up to request clarification or add additional context in comments.

11 Comments

It's important to realize this is because of type erasure in Java. It's how Java generics were implemented. At runtime Java B is always of type Object, but the compiler shoves in the casts that you needed automagically. Java made this decision for backwards compatibility. In languages such as C# type information about object B is preserved.
I don't think it has anything to do with type erasure. The reason is because it's not an actual type (it's just a type parameter). e.g. with public class MyComp implements Comparator<MyObject>, you can always instantiate MyObject in compare method.
@BheshGurung It has everything to do with type erasure. By contrast, in C# (where generic types are reified) you can do new T().
@BheshGurung No, it is not really a parameter and yes, it has to do with type erasure. Jazzepi's comment is correct and educational.
@PaulBellora: I think it depends on whether are talking Java only or generics in general.
|
2

Due to type erasure you cannot make it like that. Take a look at the following answer https://stackoverflow.com/a/6810709/860294

Comments

0

Java uses type erasure. it doesnt know the class of B, and so it doesnt know whether whatever class B ends up being at run time will have a constructor with that set of arguments.

Comments

0

The reason for this is that B can be either an interface or a class (even Abstract one). So, new B() will not be valid in case of Interface or Abstract Class. Hence, it is not allowed.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.