Amit Ben Ami
Amit Ben Ami

Reputation: 548

Java Overriding function that one of the parameters are constant in the child class

I have a service that read and write data based on a key-value pairs. The service is generic.

I want to implement a similar class, that extends the class I described, but in the base class the key is constant.

The problem is, that If I try to override the read and write functions, they both will have the key parameter in them, although it is const.

How can I implement and override in this case? Is it possible or only without the inheritence?

My BaseService.java

class BaseService {
    private HashMap<String, String> storage = new HashMap<String, String>();

    void write(String key, String value) {
        storage.put(key, value);
    }

    String read(String key) {
        return storage.get(key);
    }
}

and ChildService.java

class ChildService extends BaseService {
    static final String KEY = 'const-key';
    @override
    void write(String value) {
        storage.put(KEY, value);
    }

    @override
    String read() {
        return storage.get(KEY);
    }
}

It isn't possible to override this way since the signature is now different.

Upvotes: 0

Views: 58

Answers (1)

a.eugene
a.eugene

Reputation: 102

Try something like this:

public abstract class BaseService {
    HashMap<String, String> storage = new HashMap<String, String>();

    abstract String getKey();

    void write(String key, String value) {
        storage.put(key, value);
    }

    String read(String key) {
        return storage.get(key);
    }

    String read() {
        return storage.get(getKey());
    }

    void write(String value) {
        storage.put(getKey(), value);
    }

}

public class ChildService extends BaseService {

    static final String KEY = "const-key";

    @Override
    String getKey() {
        return KEY;
    }
}

Upvotes: 1

Related Questions