Caner
Caner

Reputation: 59258

Java: Cannot instantiate the type Foo

I'm trying to create my own version of HashMap with some utility methods.

Foo.java:

import java.util.HashMap;

public class Foo<String, Parameter> extends HashMap<String, Parameter> {

    public Foo() {
      super();
    }

    public Parameter Add(String key, MyType type) {
        return put(key, new Parameter(type)); // -> This line causes compilation error
    }
  }

The following line:

new Parameter(type);

produces Cannot instantiate the type Foo.

I checked Parameter class and it is not an abstract class/interface, why am I getting this error?

EDIT
Changing class declaration as following solved the problem:

public class Foo extends HashMap<String, Parameter> {

Upvotes: 1

Views: 6859

Answers (2)

JB Nizet
JB Nizet

Reputation: 692023

Your class declaration should be

public class Foo extends HashMap<String, Parameter> {

But it's almost always a bad idea to extend a HashMap. You should use a Map instance inside your class instead. Also, methods should always start with a lower-case letter in Java.

Upvotes: 3

Jon Skeet
Jon Skeet

Reputation: 1502526

It's not an abstract class - it's a type parameter at the moment, as is String! Your class is generic, with two type parameters. I believe you meant:

public class Foo extends HashMap<String, Parameter> {

Now it's a non-generic class.

Upvotes: 7

Related Questions