Question

I have an interface

public interface Foo<T> {
    public void bar(String s, T t);
}

I want to write a method

public void baz() {
    String hi = "Hello";
    String bye = "Bye";
    Foo<String> foo = new Foo() {
        public void bar(String s, String t) {
            System.out.println(s);
            System.out.println(s);
        }
    };
    foo.bar(hi,bye);
}

i get an error

<anonymous Test$1> is not abstract and does not override abstract method bar(String,Object) in Foo
    Foo<String> foo = new Foo() {

I'm fairly new to Java, I'm sure this is a simple mistake. how can I write this?

Was it helpful?

Solution

If you are using java 7, Type inference doesn't apply here. You have to provide the Type parameter in the constructor invoking as well.

    Foo<String> foo = new Foo<String>() {
        public void bar(String s, String t) {
            System.out.println(s);
            System.out.println(s);
        }
    };
    foo.bar(hi,bye); 

EDIT: just noticed that you have used new Foo() which is basically a raw type, you have to provide the generic type for your constructor invokation, new Foo<String>()

Related Link

OTHER TIPS

You have forgotten one <String>

public void baz() {
    String hi = "Hello";
    String bye = "Bye";
    Foo<String> foo = new Foo<String>() {
        public void bar(String s, String t) {
            System.out.println(s);
            System.out.println(s);
        }
    };
    foo.bar(hi,bye);
}

Change with below code it compile and run perfectly.

        Foo<String> foo = new Foo<String>() {
Foo<String> foo = new Foo<String>() {
  @Override
  public void bar(String s, String t) {
    System.out.println(s);
    System.out.println(s);
  }
};
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top