假设我有具体的类Cat、Dog和Parrot,以及以下接口:
class HasGuid {
HasGuid.fromId(String id);
}
我的目标是保证猫、狗和鹦鹉都有一个名为fromId
的构造函数。因此,我可以进行如下调用:
Cat.fromId("Whiskers") =returns> [A Future<Cat> object with id "Whiskers"]
Dog.fromId("Fido") =returns> [A Future<Dog> object with id "Fido"]
Parrot.fromId("Polly") =returns> [A Future<Parrot> object with id "Poly"]
fromId
通过网络进行调用,因此我将其作为Future
返回。我基本上想要一个约定,声明任何混合/扩展/实现/任何HasGuid
类的类都将有一个fromId
的命名构造函数。其中类T
上的fromId
将接受标识字符串并返回Future<T>
。
发布于 2019-05-31 22:56:06
简而言之,您不能强制一个子类实现特定的命名构造函数……您所能做的就是强制子类确保子类调用指定的构造函数。
以下面的例子为例。
class Animal {
String name;
Animal.fromName(this.name);
}
class Dog extends Animal {
Dog.withName(String name) : super.fromName(name);
}
注意以下几点...
Animal
没有零参数constructor.Dog
调用super.fromName()
构造函数,将会出现编译错误The superclass 'Animal' doesn't have a zero argument constructor.
Dog
必须调用fromName()
构造函数...它不必以相同的方式调用其命名构造函数。在本例中,请注意它的名称为withName()
.发布于 2013-04-21 15:42:01
构造函数上不能有任何保证。
实例方法的接口(实现)保证。超类(扩展)或混合(带有)也保证了实例方法,而不是构造函数。
构造函数返回它自己的类型,而不是Future。
所以它们都应该有一个静态的方法或类,但不能保证。
https://stackoverflow.com/questions/16129007
复制