2

I have this interface,

public interface IAnything {
  void m1();
  void m3();
}

And two abstract classes implementing this interface:

public abstract class AbstractThing1 implements IAnything {
  public void m1() {}
  public void m3() {}
}

public abstract class AbstractThing2 implements IAnything {
  public void m1() {}
  public void m3() {}
}

Somewhere in my code I want to call a function doSomething(kindOfAbstractClass) that perfoms m1() and m3(), among other jobs depending on kindOfAbstractClass.

How can I define and call doSomething()? I did this but it is not working. Thanks

private <T extends IAnything> void doSomething(T kindOfAbstractClass) {
...
kindOfAbstractClass.m1();
kindOfAbstractClass.m3();
...
}

doSomething(AbstractThing1.class);
Suresh Atta
  • 120,458
  • 37
  • 198
  • 307

2 Answers2

3

Try this:

private void doSomething(IAnything  kindOfAbstractClass) {
...
kindOfAbstractClass.m1();
kindOfAbstractClass.m3();
...
}
npinti
  • 51,780
  • 5
  • 72
  • 96
Cisco
  • 532
  • 1
  • 8
  • 24
  • Thanks. But should I call it like this? doSomething(AbstractThing1.class); I get errors there. –  Feb 14 '13 at 13:27
  • 1
    You have to pass and instance to the doSomething method but abstract class can not be instantiated directly so you have to extend the abstract class in order to implement its abstract methods and then pass to doSomething an instance of the new class created. – Cisco Feb 14 '13 at 13:30
3

Your problem is that you are supplying a class type rather than an instance as parameter to doSomething

Take a look at modified code below:

public class MyClass {


    void doIt(){
        doSomething(new ConcreteThing());       
    }

    private <T extends IAnything> void doSomething(T kindOfAbstractClass) {

            kindOfAbstractClass.m1();
            kindOfAbstractClass.m3();
    }

}


interface IAnything {
      void m1();
      void m3();
}

abstract class AbstractThing1 implements IAnything {
      public void m1() {}
      public void m3() {}
}


class ConcreteThing extends AbstractThing1{

}
gheese
  • 1,170
  • 1
  • 11
  • 17