简体   繁体   中英

Parameter of method in interface (without generics)?

I'm completely stuck with my amateur project. I've got MySingleton that implements MyInterface and calls MyMethod() . MyMethod() should take any of MySubcls as a parameter. The problem is how to declare MyMethod() without generics? Should use many declarations with differernt parameters or no way without generics?

Main.java => need to print values of all subclasses from single method

public class Main{
    public static void main(String[] args){
        MySubcls01 subCls01 = new MySubcls01();
        MySubcls02 subCls02 = new MySubcls02();
        MySingleton.INSTANCE.MyMethod(subCls01);
        MySingleton.INSTANCE.MyMethod(subCls02);
    }
}

enum MySingleton implements MyInterface
{
    INSTANCE;

    @Override
    public void MyMethod();// TODO - need to pass subCls01 or subCls02

    {
        System.out.println(subCls01.value);
        System.out.println(subCls02.value);
    }

}

interface MyInterface
{

    void MyMethod(); // TODO - what parameter for any subclass???

    // void MyMethod(MySubcls01 subCls01);
    // void MyMethod(MySubcls02 subCls02); => brute-force approach

    // <T> void MyMethod(T type); => shouldn't use generics

}

class MySupercls
{
    // some stuff
}

class MySubcls01 extends MySupercls
{
    String subValue = "i'm from subclass01";
}

class MySubcls02 extends MySupercls
{
    String subValue = "i'm from subclass02";
}

I think you need to use superclass type as parameter and use instanceof to determine real type.

Example:

@Override
    public void MyMethod(MySupercls inst)// TODO - need to pass subCls01 or subCls02

    {
        if (inst instanceof MySubcls01)
        {
         //cast it subclass01
        System.out.println(subCls01.value);
        }else{
         //cast it subclass02
        System.out.println(subCls02.value);
       }
    }

Note: Your code has public void MyMethod(); while implementing method. You should remove semi-colon.

使用超类作为参数,现在您可以将所有子类实例传递给myMethod()

public void MyMethod(MySuperClass yourInstance);// TODO - need to pass subCls01 or subCls02

If I understand your question correctly, you should be expecting a type common to both MySubcls01 and MySubcls02 , in this case MySupercls .

So, you should have MyMethod(MySupercls obj); as your method signature.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM