Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Instantiating a Generic Interface

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?

like image 551
cdk Avatar asked Apr 07 '26 18:04

cdk


2 Answers

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

like image 188
PermGenError Avatar answered Apr 09 '26 08:04

PermGenError


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);
}
like image 38
Stephen Connolly Avatar answered Apr 09 '26 07:04

Stephen Connolly



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!