Alf
Alf

Reputation: 1295

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";
}

Upvotes: 0

Views: 75

Answers (3)

PermGenError
PermGenError

Reputation: 46418

use superclass as a parameter, now you can pass all the subclass instances to myMethod()

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

Upvotes: 0

bn.
bn.

Reputation: 7949

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.

Upvotes: 0

kosa
kosa

Reputation: 66637

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.

Upvotes: 1

Related Questions