简体   繁体   English

Java调用相同父类的子构造函数

[英]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? FirstYear,SecondYear,ThirdYear类在哪个父类中共享?

Is there any means in java to pass child class and use its constructor? Java中是否有任何方法可以传递子类并使用其构造函数? 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. 使用单个方法创建一个接口(可以使用@FunctionalInterface注释),该方法采用一个学生ID和名称,并返回FirstYear / SecondYear / ThirdYear的父级。 Suppose you call that interface YearFactory and the method makeYear . 假设调用该接口YearFactory和方法makeYear Then FirstYear::new , SecondYear::new , and ThirdYear::new will all be objects that implement that interface. 然后, FirstYear::newSecondYear::newThirdYear::new都是实现该接口的对象。

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();
}

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

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