Design problems of using abstract class with an interface

user1474111 :

I know there are several similar topics with similar title but I have actually slightly different questions than other topics.

I have designed such a solution which abstract class implements and interface, and in the constructor it calls default method of interface to initialize a map.

Here is my interface:

   public interface ICalculator{

        int VALUE_OF_X= 10;
        int VALUE_OF_Y= 50;
        int VALUE_OF_Z = 70;


        Map<String, Integer> CHAR_VAL_MAP = new HashMap<String, Integer>(7);

        default void initValueMap(){
            CHAR_VAL_MAP.put("X", VALUE_OF_X);
            CHAR_VAL_MAP.put("Y", VALUE_OF_Y);
            CHAR_VAL_MAP.put("Z", VALUE_OF_Z);
        }

        public int calculate(final String inStr);
}

And created an abstract class:

 public abstract  class AbstractCalculator implements ICalculator{

    protected AbstractCalculator(){

        initValueMap();
    }
}

My idea was here to ensure that initValueMap method is called implicitly by the abstract class.

And the concreate class which extend abstract class is:

public class MyCalculator extends AbstractCalculator{

    public int calculate(final String romanNumberStr){
        // some logic code
    }
}

I have basically two question:

1) Is there any design problem or wrong usage of OOP concepts ? 2) In C++. using const for the parameter is good programming behaviour. But in java word, it is not so common. Is it bad to use final in method parameters?

GhostCat salutes Monica C. :

You are over complicating things. Java 9 added some nice of() methods to the Collections utility class. You can use those to create a map filled with values without the need to call an extra init method. Then you pass that map instance to new HashMap() to get that data into a modifiable map instance. And with older java, you can always write a method that creates and returns a prefilled map. There is no need to do creation and filling like you do (in separate pieces of code).

For the record: you understand that all fields of an interface are static by default and thus shared between all code using them?!

Regarding final, there are quite some differences to const from C++. The only thing that a final parameter gives you is checking that prevents you from inadvertently writing to a parameter. It can be useful to have that, but most people simply don't use it because they add such little gain, but make code quite harder to read.

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=145600&siteId=1