我有2节课
class Immutable {
public int i;
public static Immutable create(int i){
return new Immutable(i);
}
private Immutable(int i){this.i = i;}
public int getI(){return i;}
}
和
class Immutable1 {
public int i;
public static Immutable1 create(int i){
return new Immutable1(i);
}
private Immutable1(int i){this.i = i;}
public int getI(){return i;}
}
两者具有相同的方法和相同的实例变量。根据我对类的理解状态,它们是相同的(int i),并且都具有相同的行为(方法数量相同)
因此,一个是另一个的精确副本。
如果我在另一堂课
Immutable immutable=Immutable.create(1);
Immutable1 immutable1=Immutable1.create(1);
immutable1=immutable;// I get error here
错误是类型不匹配:无法从不可变转换为不可变1
Java使用标称类型(仅名称,以及声明要继承/实现的内容)。现在的问题是描述结构类型的Java并没有支持。
在这种情况下,由于Immutable和Immutable1类型之间没有声明的指定关系,因此会出现类型错误。
现在,即使存在关系,也请记住,只有子类型可以隐式分配给超类型;如果没有在运行时可能失败的显式下调转换,则不可能实现相反的操作。
因此,当且仅当Immutable扩展Immutable1-即,当前代码才是类型有效的。 class Immutable extends Immutable1 ..
Andrey指出了我非常喜欢的另一种解决方案,即让两个类都实现相同的接口。由于两个类都都实现了ImmutableInterface,因此这两个类都仅是类型等效的,但仍消除了类之间的继承关系。
interface ImmutableInterface {
int getI();
}
class Immutable implements ImmutableInterface ..
class Immutable1 implements ImmutableInterface ..
// The resulting object types are implicitly upcast to
// the common (and named) interface type which is trivially assignable to
// a variable of the same type; no need to worry about subtypes here.
ImmutableInterface immutable=Immutable.create(1);
ImmutableInterface immutable1=Immutable1.create(1);
immutable1 = immutable;
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句