简体   繁体   English

接口中方法的参数(无泛型)?

[英]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() . 我有MySingleton实现MyInterface并调用MyMethod() MyMethod() should take any of MySubcls as a parameter. MyMethod()应该采用MySubcls中的任何一个作为参数。 The problem is how to declare MyMethod() without generics? 问题是如何在没有泛型的情况下声明MyMethod() Should use many declarations with differernt parameters or no way without generics? 应该使用带有不同参数的许多声明还是没有泛型的方法?

Main.java => need to print values of all subclasses from single method Main.java =>需要从单个方法打印所有子类的值

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. 我认为您需要使用超类类型作为参数,并使用instanceof来确定实型。

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(); 注意:您的代码具有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 . 如果我正确理解了您的问题,那么您应该期望MySubcls01MySubcls02都具有通用类型,在本例中为MySupercls

So, you should have MyMethod(MySupercls obj); 因此,您应该具有MyMethod(MySupercls obj); as your method signature. 作为您的方法签名。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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