balicekt
balicekt

Reputation: 613

Issue with interface and parameter

I have problem with interface and parameters:

public class Functions {
  public static Double getInfoSum(TreeMap<String, Iinterface> map){
    ....some counting
  }
}

public class ExampleClass {

  private TreeMap<String, ExampleClassItem > xxxx;

  public static void SomeFunction(){
    Functions.getInfoSum(xxxx); //HERE IS ERROR 
  }
}


public class ExampleClassItem implements Iinterface {

  .....

}

Is there any other possibility except do this:

private TreeMap<String, ExampleClassItem > xxxx; -----> private TreeMap<String, Iinterface > xxxx;

because I need to work with ExampleClassItem there are specific functions which can be not in Interface.

Upvotes: 2

Views: 49

Answers (2)

user3207081
user3207081

Reputation: 1551

First of all

 public static void SomeFunction(){
   Functions.getInfoSum(xxxx); //HERE IS ERROR 
 }

Your "xxxx" is not static, and your method is static so you can't use non static fields inside your method.

You can change your method and use "?" wildcard

public static Double getInfoSum(TreeMap<String, ? extends Iinterface> map){

So you can pass here anything that extends Iinterface.

ExampleClassItem is subtype of Iinterface but TreeMap<String, ExampleClassItem>

is not subtype of TreeMap<String, Iinterface>

Upvotes: 0

Eran
Eran

Reputation: 393821

You can change

public static Double getInfoSum(TreeMap<String, Iinterface> map){
 ....some counting
}

to

public static Double getInfoSum(TreeMap<String, ? extends Iinterface> map){
 ....some counting
}

This will allow you to pass a TreeMap<String, ExampleClassItem> to this method.

Upvotes: 4

Related Questions