JerryWu JerryWu - 6 months ago 14
Java Question

C#: substituting a subclass/subtype of a parameter when overiding a method like Java do?

In java, i can do this:

public class A {
//...
}

public class B extends A {
//...
}

public interface I {
void test(A a);
}

public class C implements I {
//i can use class B as parameters in java but how to do in .net ?
// not work in .net
@override
public void test(B b){

}
}


I can use class B as parameters in java but how to do in .net ?

AGB AGB
Answer

In order to implement the interface member I.test(A a), the the test() method of the C must be public, non-static, and have the same name and signature as the interface member.

C.test fails one criterion: it does not have the same signature as I.test.


Option 1: Implement the Interface

public class A {
    //...
}

public class B extends A {
    //...
}

public interface I {
    void test(A a);
}

public class C implements I {
    public void test(A a){

    }
}

of course you can still pass B instances into C.test:

var b = new B();
var c = new C();
c.test(b);//works just fine

Option 2: Change the Interface

Say your implementation of I in C depends on a property present on B but not on A. Suppose further that it makes sense that I.test is a perfectly valid method to write so long as the parameter being passed in extends A.

In that scenario, you can try something like this:

public class A
{
    //...
}

public class B : A
{
    //...
}

public interface I<T> where T : A
{
    void test(T a);
}

public class C : I<B>
{
    public void test(B b)
    {

    }
}

Which utilizes generics as well as generic type constraints and seems like it may be a little closer to what you are trying to represent/accomplish.

Comments