繁体   English   中英

与抽象getters和安装员的抽象类

[英]Abstract class with abstract getters and setters

假设我有一个抽象类List ,我想创建一个扩展这个名为MyList类的类。 将抽象getter和setter放在抽象类中,迫使MyList覆盖它们是不好的编程习惯吗?

我想这样做的原因就像为List每个特化设置一个不同的容量。 所以我会做这样的事情:

public abstract class List {
    public abstract int getMaximumSize();
}

public class MyList extends List {
    @Override
    public int getMaximumSize() {
        return 10;
    }
}

我还有另一个例子,我把一个setter放在抽象类中,但现在我忘记了。

IMO,这是一种合理的方法(模数设置器。不要在抽象,非抽象或任何​​其他类型的文件中设置setter)。

这里有一个问题 - 如果你班级的实施者是白痴,会发生什么? 考虑

public abstract class List {
    public abstract int getMaximumSize();
}

public class MyList extends List {
    @Override
    public int getMaximumSize() {
        // negative?!?!
        return -10;
    }
}

如果你想避免这种情况,你可以这样做:

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

在这种情况下,我会推荐一个接口,例如

public interface MaxList extends List // or some better name {
    public int getMaxSize();
}

然后是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;
    }
}

注意:我假设您要扩展java.util.List的实现。 如果不这样做,则不需要MaxList接口来扩展java.util.ListMaxList以扩展java.util.ArrayList

我想如果你想强迫每个孩子都有getter \\ setter,那就没关系了。 最终,如果它满足您的需求,那就没关系,我宁愿问是否有更好的方法来实现这种行为。

暂无
暂无

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

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