简体   繁体   中英

Java Calling child constructors of same parent class

Any way to simplify this?

switch (student.getYear())
   case 1:
      new FirstYear(student.getId(), student.getName());
      break;
   case 2:
      new SecondYear(student.getId(), student.getName());
      break;
   case 3:
      new ThirdYear(student.getId(), student.getName());
      break;
   default:
      break;

where FirstYear, SecondYear, ThirdYear class shares same parent class?

Is there any means in java to pass child class and use its constructor? if they share same constructor structure?

ie.


public static void registerStudent(final Class yearClazz) {
     new yearClazz(student.getId(), student.getName()).save(); //???
}

something like this?

You can use a method reference and functional interfaces. Create an interface (optionally annotated with @FunctionalInterface ) with a single method that takes a student ID and name, and returns whatever the parent of FirstYear/SecondYear/ThirdYear is. Suppose you call that interface YearFactory and the method makeYear . Then FirstYear::new , SecondYear::new , and ThirdYear::new will all be objects that implement that interface.

switch (student.getYear())
   case 1:
      fac = FirstYear::new;
      break;
   case 2:
      fac = SecondYear::new;
      break;
   case 3:
      fac = ThirdYear::new;
      break;
   default:
      break;
public static void registerStudent(final YearFactory fac) {
     fac.makeYear(student.getId(), student.getName()).save();
}

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