jeudi 17 mai 2018

Create an object of the class I'm in

I have a bunch of classes let's call them Foo1, Foo2, Foo3. Each of them shares a parent SuperFoo and has a similar main function. Each creates an instance of the class and then calls bar() on it.

Essentially, what I have now is:

class Foo1 extends SuperFoo {
  public static void main(String[] args) {
    new Foo1().bar();
  }
}

class Foo2 extends SuperFoo {
  public static void main(String[] args) {
    new Foo2().bar();
  }
}

class Foo3 extends SuperFoo {
  public static void main(String[] args) {
    new Foo3().bar();
  }
}

Basically, this means I'm writing the same function over and over again.

Could I just have a main in SuperFoo that is inherited and uses reflection to create an instance of the subclass? Or is there some other way to merge these into a single function?





Aucun commentaire:

Enregistrer un commentaire