简体   繁体   中英

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 . Is it bad programming practice to put abstract getters and setters in the abstract class, forcing MyList to override them?

The reason I want to do this is something like setting a constant capacity that is different for each specialization of a 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.

IMO, this is a reasonable approach (modulo setters. Don't do setters in abstract, non-abstract, or any other types of files).

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

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 . If you do not, there is no need for MaxList interface to extend java.util.List or MyList to extends java.util.ArrayList

I think it is ok if you want to force every child to have 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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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