在 Typescript 中,有一个多态返回类型的概念this
。
https://www.typescriptlang.org/docs/handbook/advanced-types.html#polymorphic-this-types
示例:
export abstract class Animal {
private name: string;
public setName(name: string): this {
this.name = name;
return this;
}
}
export class Dog extends Animal {
private breed: string;
public setBreed(breed: string): this {
this.breed = breed;
return this;
}
}
export class FluffyDog extends Dog {
private fluffiness: number;
public setFluffiness(fluffiness: number): this {
this.fluffiness = fluffiness;
return this;
}
}
export class Main {
constructor() {
const dog: FluffyDog = new FluffyDog()
.setName('Fluffy')
.setFluffiness(10)
.setBreed('Lab');
}
}
Java中有什么等价的吗?我想出的最好的是:
public abstract class Animal<T extends Animal<T>> {
private String name;
public T setName(String name) {
this.name = name;
return (T)this;
}
}
class Dog extends Animal<Dog> {
private String breed;
public Dog setBreed(String breed) {
this.breed = breed;
return this;
}
}
class Main {
static {
Dog dog = new Dog()
.setName("Fluffy")
.setBreed("Lab");
}
}
或这个:
public abstract class Animal {
private String name;
public <T extends Animal> T setName(String name) {
this.name = name;
return (T)this;
}
}
class Dog extends Animal {
private String breed;
public <T extends Dog> T setBreed(String breed) {
this.breed = breed;
return (T)this;
}
}
class FluffyDog extends Dog {
private Long fluffiness;
public <T extends FluffyDog> T setFluffiness(Long fluffiness) {
this.fluffiness = fluffiness;
return (T)this;
}
}
class Main {
static {
FluffyDog dog = new FluffyDog()
.<FluffyDog>setName("Fluffy")
.setFluffiness(10L)
.setBreed("Lab");
}
}
第一个似乎只能被子类化一次。
第二个在某些情况下需要显式类型参数。
有没有办法在 Java 中返回多态 this ?