user997112
user997112

Reputation: 30615

Interface with generic parameters- can't get it to compile

I have an interface like so:

public interface MyInterface<E extends Something1> {
    public void meth1(MyClass1<E> x);
}

and I have a subclass whose superclass implements the above interface:

public class MyClass2<E extends Something1> extends Superclass{

    public MyClass2(){

    }

    public void meth1(MyClass1 x) {
        // TODO Auto-generated method stub

    }
}

superclass:

public abstract class Superclass<E extends Something1> implements MyInterface{
    MyClass1<E> x;
    protected E y;

    public Superclass(){

    }
}

MyClass1:

public abstract class Myclass1<E extends Something1> {

    public Myclass1(){

    }
}

the problem is that the parameter for meth1() is supposed to be generic. If I do MyClass1 it doesn't like it and the only way I can get it to compile is by leaving out generic parameters- which feels wrong.

What's going wrong?

Upvotes: 0

Views: 66

Answers (3)

munyengm
munyengm

Reputation: 15479

Here are your classes now parameterised appropriately:

class Something1 { }

public interface MyInterface<E extends Something1> {
    public void meth1(MyClass1<E> x);
}

// and I have a subclass whose superclass implements the above interface:
public class MyClass2<E extends Something1>
    extends Superclass<E> {

    public MyClass2() { }

    public void meth1(MyClass1<E> x) { }
}

// superclass:
public abstract class Superclass<E extends Something1> implements
        MyInterface<E> {
    MyClass1<E> x;
    protected E y;

    public Superclass() { }
}

// MyClass1:
public abstract class MyClass1<E extends Something1> {

    public MyClass1() {

    }
}

Upvotes: 1

Sergii Zagriichuk
Sergii Zagriichuk

Reputation: 5399

Not mandatory

public abstract class Superclass<E extends Something1> implements MyInterface<E>

Mandatory

public class MyClass2<E extends Something1> extends Superclass<E>

All will compile and method will be generic

Upvotes: 1

Miquel
Miquel

Reputation: 15675

So, this compiles, where MyClass1 happens to be a List: Did I miss something? Is your code different? If it's all the same, there might be something going on with your choice of MyClass1. Also, we're missing the superclass of MyClass2, which could also be problematic...

import java.util.List;

public class MyClass2<E extends Object> extends Object{

    public MyClass2(){

    }

    public void meth1(List<E> x) {
        // TODO Auto-generated method stub

    }
}

interface MyInterface<E extends Object> {
    public void meth1(List<E> x);
}

Upvotes: 1

Related Questions