[英]Abstract class with abstract getters and setters
Say I have an abstract class List
and I want to make a class that extends this class called MyList
. 假设我有一个抽象类List
,我想创建一个扩展这个名为MyList
类的类。 Is it bad programming practice to put abstract getters and setters in the abstract class, forcing MyList
to override them? 将抽象getter和setter放在抽象类中,迫使MyList
覆盖它们是不好的编程习惯吗?
The reason I want to do this is something like setting a constant capacity that is different for each specialization of a List
. 我想这样做的原因就像为List
每个特化设置一个不同的容量。 So I would do something like this: 所以我会做这样的事情:
public abstract class List {
public abstract int getMaximumSize();
}
public class MyList extends List {
@Override
public int getMaximumSize() {
return 10;
}
}
I also had another example where I put a setter in the abstract class but now I forget. 我还有另一个例子,我把一个setter放在抽象类中,但现在我忘记了。
IMO, this is a reasonable approach (modulo setters. Don't do setters in abstract, non-abstract, or any other types of files). IMO,这是一种合理的方法(模数设置器。不要在抽象,非抽象或任何其他类型的文件中设置setter)。
One issue here though - what happens if the implementor of your class is an idiot? 这里有一个问题 - 如果你班级的实施者是白痴,会发生什么? consider 考虑
public abstract class List {
public abstract int getMaximumSize();
}
public class MyList extends List {
@Override
public int getMaximumSize() {
// negative?!?!
return -10;
}
}
If you want to avoid this, you could do something like this: 如果你想避免这种情况,你可以这样做:
public abstract class List {
// this is the method to override
protected abstract int getMaximumSizeInternal();
// and this method is final. Can't mess around with that!
public final int getMaximumSize() {
int x = getMaximumSizeInternal();
if (x < 0) { throw new RuntimeException ("Apologies, sub-classer is an idiot"); }
return x;
}
public class MyList extends List {
@Override
protected int getMaximumSizeInternal() {
// negative?!?!
return -10;
}
}
In this case, I would recommend an interface eg 在这种情况下,我会推荐一个接口,例如
public interface MaxList extends List // or some better name {
public int getMaxSize();
}
Then for MyList
然后是MyList
public class MyList extends ArrayList implements MaxList {
// The above assumes you want to extend ArrayList. You may extend some other
// List implementation or provide your own.
@Override
public int getMaximumSize() {
return 10;
}
}
NOTE: I am assuming you want to extend an implementation of java.util.List
. 注意:我假设您要扩展java.util.List
的实现。 If you do not, there is no need for MaxList
interface to extend java.util.List
or MyList to extends java.util.ArrayList
如果不这样做,则不需要MaxList
接口来扩展java.util.List
或MaxList
以扩展java.util.ArrayList
I think it is ok if you want to force every child to have getter\\setter. 我想如果你想强迫每个孩子都有getter \\ setter,那就没关系了。 Eventually, if it satisfies your needs, it is ok, I would rather ask if there is a better way to achieve this behaviour. 最终,如果它满足您的需求,那就没关系,我宁愿问是否有更好的方法来实现这种行为。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.